3. SQL Basic Overview
What is SQL
SQL stands for Structured Query Language and can be pronounced as
SQL or sequel – (Structured Query Language) . Defined, SQL is a query
language used for accessing and modifying information in one or more data
tables and rows of a database.
SQL DataBase
In a simple manner, SQL is a non-procedural, English-like language that
processes data in groups of records rather than one record at a time.
Few SQL functions of are:
Store data
Modify data
Retrieve data
Delete data
Create tables and other database objects
A Brief History of SQL
SQL Database Design
IBM first developed SQL in 1970s. Also it is an ANSI/ISO standard. It has
become a Standard Universal Language used by most of the relational
database management systems (RDBMS). Some of the RDBMS systems are:
Oracle, Microsoft SQL server, Sybase etc.
View 9
1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for databases.
1974 − Structured Query Language appeared.
1978 − IBM worked to develop Codd's ideas and released a product
named System/R.
1986 − IBM developed the first prototype of relational database and
standardized by ANSI. The first relational database was released by
Relational Software which later came to be known as Oracle.
4. Most of these have provided their own implementation extensions, thus
enhancing their RDBMS system features and making it a powerful tool.
These RDBMS systems, all use the popular SQL commands SELECT, UPDATE,
DELETE, INSERT, WHERE in similar format.
SQL Database Table
SQL database is constructed of a number of tables. In a business,
SQL tables would be used to divide and simplify the different areas of the
operation: Table for Customers, one for Vendors, Employees and so on.
SQL Database Table Columns
Each SQL table is made up of a number of columns, referred to as
fields and run along the top of the table. Sql columns or fields have their
content (object/data/info) defined into character types; such as text, date,
numeric, integer, length to name a few.
SQL Database Table Rows
Each SQL table row, referred to a record, is located in the left
column of the table. Sql record row will contain a string of data containing
data matching up to each column field across the top. So, in a Customer
table each customer record would consist of one row with data for the
customer ID number, customer name, address, phone ... email and so on.
Simple Overview of various SQL query
SQL Query Types
SELECT Statement Retrieve records from a table
SELECT LIMIT Statement Retrieve records from a table and limit results
SELECT TOP Statement Retrieve records from a table and limit results
INSERT Statement Insert records into a table
UPDATE Statement Update records in a table
DELETE Statement Delete records from a table
TRUNCATE TABLE
Statement
Delete all records from a table (no rollback)
UNION Operator Combine 2 result sets (removes duplicates)
UNION ALL Operator Combine 2 result sets (includes duplicates)
5. INTERSECT Operator Intersection of 2 result sets
MINUS Operator Result set of one minus the result set of
another
EXCEPT Operator Result set of one minus the result set of
another
SQL Comparison Operators
Comparison Operators Operators such as =, <>, !=, >, <, and so on
SQL Joins
JOIN Tables Inner and Outer joins
SQL Aliases
ALIASES Create a temporary name for a column or table
SQL Clauses
DISTINCT Clause Retrieve unique records
FROM Clause List tables and join information
WHERE Clause Filter results
ORDER BY Clause Sort query results
GROUP BY Clause Group by one or more columns
HAVING Clause Restrict the groups of returned rows
SQL Functions
COUNT Function Return the count of an expression
SUM Function Return the sum of an expression
MIN Function Return the min of an expression
MAX Function Return the max of an expression
AVG Function Return the average of an expression
7. Query Language DDL, DML, DCL
Data-definition language (DDL): The SQL DDL provides commands for
defining relation schemas, deleting relations, and modifying relation schemas.
DDL - Data Definition Language
Command & Description
CREATE
Creates a new table, a view of a table, or other objother
objectsatabase.
ALTER
Modifies an existing database object, such as a table.
DROP
Deletes an entire table, a view of a table or other objects in the
database.
Interactive data-manipulation language (DML): The SQL DML includes a
query language based on both the relational algebra and the tuple relational
calculus. It includes also commands to insert tuples into, delete tuples from, and
modify tuples in the database.
DML - Data Manipulation Language
Command & Description
SELECT
Retrieves certain records from one or more tables.
INSERT
Creates a record.
UPDATE
Modifies records.
View 9
10. Connect with a system user in SQL
Create a new user inside Oracle Database
After installation of Oracle software. We have to create a user inside it. In this
tutorial, we are going to show you how to create a new user. So let's start.
To create a new user. Start SQL PLUS form your windows menu. It flows the
below statements for SQL 11g release 2 version.
For this, you have to login in the system user for the highest privilege. First I
will tell you how to Connect to the Oracle Database from SQL*Plus.
To connect to Oracle Database from SQL*Plus: (Using
SQL PLUS)
After typing the username and password it will look like this. By default, the
username is system and password in that password which you gave at the
time of installation, in my case the password is alone#i#4
View 6
11. To connect to Oracle Database from SQL*Plus: (Using
CMD)
1. If you are on a Windows system, display a Windows command prompt.
2. At the command prompt, type sqlplus and press the key Enter.
SQL*Plus starts and prompts you for your username.
3. Type your username and press the key Enter.
SQL*Plus prompts you for your password.
4. Type your password and press the key Enter.
For security, your password is not visible on your screen.
The system connects you to an Oracle Database instance.
You are in the SQL*Plus environment. At the SQL> prompt, you can enter
and run SQL*Plus commands, SQL statements, PL/SQL statements, and
operating system commands.
To exit SQL*Plus, type exit and press the key Enter.
Exiting SQL*Plus ends the SQL*Plus session, but does not shut down
the Oracle Database instance.
SQL*Plus: Release 11.2.0.1.0 Production on Wed Jul 18 22:30:24 2018
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Enter user-name: system
Enter password: alone#i#4 (For security, your password is not visible on your
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL>
13. Create a Database User in SQL
As always, begin by connecting to your server where Oracle is hosted, then
connect to Oracle itself as the SYSTEM account.
The SYSTEM account is one of a handful of predefined administrative
accounts generated automatically when Oracle is installed. SYSTEM is capable
of most administrative tasks, but the task we’re particularly interested in is
account management.
Creating a User
Once connected as SYSTEM , simply issue the CREATE USER command to
generate a new account.
Run the below query to check whether you are in SYSTEM user or not
If you don't know how to connect with SYSTEM user please see the previous
tutorial
SQL> SHOW user;
USER is "SYSTEM"
SQL>
CREATE USER user_name IDENTIFIED BY MyPassword;
Example
Here I am creating one user. In my case user name is Username: atnylaUser
and password is: rumman_ansari
SQL> CREATE USER atnylaUser IDENTIFIED BY rumman_ansari;
User created.
SQL>
Here we’re simply creating a atnylaUser account that is IDENTIFIED or
authenticated by the specified rumman_ansari .
The Grant Statement
View 7
14. With our user_name new account created, we can now begin adding
privileges to the account using the GRANT statement. GRANT is a very
powerful statement with many possible options, but the core functionality is
to manage the privileges of both users and roles throughout the database.
Providing Roles
Typically, you’ll first want to assign privileges to the user through attaching
the account to various roles, starting with the CONNECT role:
GRANT CONNECT TO user_name;
Example
SQL> GRANT CONNECT TO atnylaUser;
Grant succeeded.
SQL>
In some cases to create a more powerful user, you may also consider adding
the RESOURCE role (allowing the user to create named types for custom
schemas) or even the DBA role, which allows the user to not only create
custom named types but alter and destroy them as well.
GRANT CONNECT, RESOURCE, DBA TO user_name;
Example
SQL> GRANT CONNECT, RESOURCE, DBA TO atnylaUser;
Grant succeeded.
SQL>
Assigning Privileges
Next you’ll want to ensure the user has privileges to actually connect to the
database and create a session using GRANT CREATE SESSION . We’ll also
combine that with all privileges using GRANT ANY PRIVILEGES .
GRANT CREATE SESSION GRANT ANY PRIVILEGE TO user_name;
21. Create table in SQL
The SQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.
Syntax
The following SQL statement is syntax for CREATE TABLE.
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype
);
CREATE TABLE is the keyword telling the database system what you want to
do. In this case, you want to create a new table. The unique name or
identifier for the table follows the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what
sort of data type it is. The syntax becomes clearer with the following example.
A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement.
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Example
This a example SQL statement for the above syntax.
The following code block is an example, which creates a Human table with an
ID as NOT NULL are the constraints showing that these fields cannot be
NULL while creating records in this table ?
View 3
22. CREATE TABLE Human(
ID INT NOT NULL,
FIRST_NAME VARCHAR (20) NOT NULL,
LAST_NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2)
);
After placing the above code it will show you Table created. statement.
Example From SQL PLUS screen
SQL> CREATE TABLE Human(
2 ID INT NOT NULL,
3 FIRST_NAME VARCHAR (20) NOT NULL,
4 LAST_NAME VARCHAR (20) NOT NULL,
5 AGE INT NOT NULL,
6 ADDRESS CHAR (25) ,
7 SALARY DECIMAL (18, 2)
8 );
Table created.
SQL>
You can verify if your table has been created successfully by looking at the
message displayed by the SQL server, otherwise you can use the DESC
command as follows ?
Remember: table name should be always unique. Means no two table
have same name. table name should be always different
Another Example with primary key
SQL> DESC Human;
Name Null? Type
----------------------------------------- -------- --------------------------
ID NOT NULL NUMBER(38)
FIRST_NAME NOT NULL VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(20)
AGE NOT NULL NUMBER(38)
ADDRESS CHAR(25)
SALARY NUMBER(18,2)
SQL>
23. Syntax
The following SQL statement is syntax for CREATE TABLE with primary key.
CREATE TABLE Human(
ID INT NOT NULL,
FIRST_NAME VARCHAR (20) NOT NULL,
LAST_NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Example
This a example SQL statement for the above syntax.
SQL> CREATE TABLE Human(
2 ID INT NOT NULL,
3 FIRST_NAME VARCHAR (20) NOT NULL,
4 LAST_NAME VARCHAR (20) NOT NULL,
5 AGE INT NOT NULL,
6 ADDRESS CHAR (25) ,
7 SALARY DECIMAL (18, 2),
8 PRIMARY KEY (ID)
9 );
Table created.
SQL>
You can verify if your table has been created successfully by looking at the
message displayed by the SQL server, otherwise you can use the DESC
command as follows ?
SQL> DESC Human;
Some Another Examples
Example 1: CREATE TABLE Persons
24. SQL Syntax
CREATE TABLE Persons (
PersonID int,
FirstName varchar(255),
LastName varchar(255),
Address varchar(255),
City varchar(255)
);
Example 2: CREATE TABLE Client_master_21
SQL Syntax
CREATE TABLE Client_master_21(client_no varchar2(6) not null,
name varchar2(20) not null,
address1 varchar2(30),
address2 varchar2(30),
city varchar2(15) not null,
pincode number(6) not null,
state varchar2(15) not null,
bal_due number(10,2) not null
);
Example 3: CREATE TABLE Product_master_21
PERSONID NUMBER(38)
FIRSTNAME VARCHAR2(255)
LASTNAME VARCHAR2(255)
ADDRESS VARCHAR2(255)
CITY VARCHAR2(255)
CLIENT_NO NOT NULL VARCHAR2(6)
NAME NOT NULL VARCHAR2(20)
ADDRESS1 VARCHAR2(30)
ADDRESS2 VARCHAR2(30)
CITY NOT NULL VARCHAR2(15)
PINCODE NOT NULL NUMBER(6)
STATE NOT NULL VARCHAR2(15)
BAL_DUE NOT NULL NUMBER(10,2)
25. SQL Syntax
CREATE TABLE Product_master_21( product_no varchar2(6) not null,
description varchar2(15) not null,
profit_percent number(4,2) not null,
unit_measure varchar2(10) not null,
qty_on_hand number(8) not null,
recode_lvl number(8) not null,
sell_price number(8,2) not null,
cost_price number(8,2) not null
);
Example 4: CREATE TABLE Salesman_master_21
SQL Syntax
PRODUCT_NO NOT NULL VARCHAR2(6)
DESCRIPTION NOT NULL VARCHAR2(15)
PROFIT_PERCENT NOT NULL NUMBER(4,2)
UNIT_MEASURE NOT NULL VARCHAR2(10)
QTY_ON_HAND NOT NULL NUMBER(8)
RECODE_LVL NOT NULL NUMBER(8)
SELL_PRICE NOT NULL NUMBER(8,2)
COST_PRICE NOT NULL NUMBER(8,2)
SALESMAN_NO VARCHAR2(6)
SALESMAN_NAME NOT NULL VARCHAR2(20)
ADDRESS1 NOT NULL VARCHAR2(30)
ADDRESS2 NOT NULL VARCHAR2(30)
CITY NOT NULL VARCHAR2(20)
PINCODE NOT NULL NUMBER(6)
STATE NOT NULL VARCHAR2(15)
SAL_AMT NOT NULL NUMBER(8,2)
TGT_TO_GET NOT NULL NUMBER(6,2)
YTD_SALES NOT NULL NUMBER(6,2)
REMARKS NOT NULL VARCHAR2(10)
27. Drop table in SQL
The SQL DROP TABLE statement is used to remove a table definition and all
the data, indexes, triggers, constraints and permission specifications for that
table.
Note: Be careful before dropping a table. Deleting a table will result in
loss of complete information stored in the table!
Syntax
The following SQL statement is the syntax for DROP TABLE
DROP TABLE table_name;
Example
A Human table already present in my database. Let us first verify the Human
table and then we will delete it from the database as shown below ?
This means that the Human table is available in the database, so let us now
drop it as shown below.
Now Drop the table using DROP TABLE table_name query.
SQL> DROP TABLE Human;
Table dropped.
Here it is, our Human table is deleted. Now Let us verify again the Human
table.
View 3
SQL> DESC Human;
Name Null? Type
----------------------------------------- -------- ----------------------------
ID NOT NULL NUMBER(38)
FIRST_NAME NOT NULL VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(20)
AGE NOT NULL NUMBER(38)
ADDRESS CHAR(25)
SALARY NUMBER(18,2)
29. Insert Data into the table
The SQL INSERT INTO Statement is used to add new rows of data to a table
in the database.
Syntax
There are two basic syntaxes of the INSERT INTO statement which are
shown below.
The following SQL statement is syntax for INSERT INTO database
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns
in the table into which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are
adding values for all the columns of the table. But make sure the order of the
values is in the same order as the columns in the table.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Rumman','Ansari', 32, 'Ahmedabad', 2000.00 );
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Musar','Mondal', 25, 'Delhi', 1500.00 );
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Osman','Sk', 23, 'Kota', 2000.00 );
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Badsha','Roy', 25, 'Mumbai', 6500.00 );
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Alamgir','Roy', 27, 'Bhopal', 8500.00 );
INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Rajesh','Roy', 22, 'MP', 4500.00 );
View 5
30. You can create a record in the Human table by using the second syntax as
shown below.
INSERT INTO Human
VALUES (7, 'Rambo','Azmi', 24, 'Indore', 10000.00 );
After installation it will show like the below
SQL> INSERT INTO Human (ID,FIRST_NAME,LAST_NAME,AGE,ADDRESS,SALARY)
2 VALUES (2, 'Musar','Mondal', 25, 'Delhi', 1500.00 );
1 row created.
All the above statements would produce the following records in the Human
table as shown below.
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in
the "FIRSTNAME", "LASTNAME", and "ADDRESS" columns:
But Remember other columns should not be NOT NULL columns
INSERT INTO Human (FIRST_NAME,LAST_NAME,ADDRESS)
VALUES ('ib','MAM','Delhi');
Populate one table using another table
You can populate the data into a table through the select statement over
another table; provided the other table has a set of fields, which are required
to populate the first table.
Here is the syntax :
INSERT INTO First_Table_Name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM Second_Table_Name
[WHERE condition];
---------- -------------------- -------------------- ---------- ----------------
ID FIRST_NAME LAST_NAME AGE ADDRESS
---------- -------------------- -------------------- ---------- ----------------
1 Rumman Ansari 32 Ahmedabad
2 Musar Mondal 25 Delhi
3 Osman Sk 23 Kota
4 Badsha Roy 25 Mumbai
5 Alamgir Roy 27 Bhopal
6 Rajesh Roy 22 MP
7 Rambo Azmi 24 Indore
---------- -------------------- -------------------- ---------- ----------------
31. Insert Data into Client_master_21 table
Sql Query
Insert Data into Product_master_21 table
SQL Code
Insert Data into Salesman_master_21 table
------ | ---------- --------------- | ---------- | --------------- | ---------
CLIENT | NAME | PINCODE | STATE | BAL_DUE
------ | ---------- --------------- | ---------- | --------------- | ---------
C00001 | Amit Saman | Kolkata | 700001 | West | 15000.
| ta | | | Bengal |
C00002 | Tapos Das | Mumbai | 400012 | Maharashtra |
C00003 | Anup Maiti | Mumbai | 400014 | Maharashtra | 500
C00004 | Bimal Roy | Chennai | 600018 | Tamil Nadu |
C00005 | Moni Kar | Kolkata | 700017 | West Bengal | 200
C00006 | AR Khan | Delhi | 700024 | Delhi |
------ | ---------- --------------- | ---------- | --------------- | ---------
INSERT INTO Client_master_21 VALUES('C00001','Amit Samanta','','','Kolkata',70
INSERT INTO Client_master_21 VALUES('C00002','Tapos Das','','','Mumbai',400012
INSERT INTO Client_master_21 VALUES('C00003','Anup Maiti','','','Mumbai',40001
INSERT INTO Client_master_21 VALUES('C00004','Bimal Roy','','','Chennai',60001
INSERT INTO Client_master_21 VALUES('C00005','Moni Kar','','','Kolkata',700017
INSERT INTO Client_master_21 VALUES('C00006','AR Khan','','','Delhi',700024,'D
------ | --------------- | -------------- | ---------- | ----------- | ---------
PRODUC | DESCRIPTION | PROFIT_PERCENT | UNIT_MEASU | QTY_ON_HAND | RECODE_
------ | --------------- | -------------- | ---------- | ----------- | ---------
P00001 | 1.44 | 5 | piece | 100 | 2
| floppies | | | |
P03453 | 6 | 5 | piece | 10 | 2
P06734 | 5 | 5 | piece | 20 | 2
P07868 | 5 | 5 | piece | 10 | 2
P07885 | 25 | 5 | piece | 10 | 2
------ | --------------- | -------------- | ---------- | ----------- | ---------
INSERT INTO Product_master_21 VALUES('P00001','1.44 floppies',5,'piece',100,2
INSERT INTO Product_master_21 VALUES('P03453','6',5,'piece',10,20,3,11280);
INSERT INTO Product_master_21 VALUES('P06734','5',5,'piece',20,20,5,100);
INSERT INTO Product_master_21 VALUES('P07868','5',5,'piece',10,20,3,1000);
INSERT INTO Product_master_21 VALUES('P07885','25',5,'piece',10,20,3,5100);