0% found this document useful (0 votes)
3 views25 pages

SQL Commands

The document provides SQL commands for creating, dropping, renaming databases and tables, as well as managing table structures through ALTER commands. It explains the concepts of primary keys, foreign keys, unique keys, and composite keys, along with their differences and usage in SQL. Additionally, it covers SELECT statements for retrieving data from tables with various conditions.

Uploaded by

Deepanshu Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

SQL Commands

The document provides SQL commands for creating, dropping, renaming databases and tables, as well as managing table structures through ALTER commands. It explains the concepts of primary keys, foreign keys, unique keys, and composite keys, along with their differences and usage in SQL. Additionally, it covers SELECT statements for retrieving data from tables with various conditions.

Uploaded by

Deepanshu Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

To CREATE Database:

CREATE DATABASE database_name;

Note :We should always remember that database name should be unique in the RDBMS.

To DROP Database

DROP DATABASE database_name;

Note : If we delete or drop the database, all the tables and views will also be deleted. So be careful
while using this command.

To Rename database:

RENAME DATABASE old_db_name TO new_db_name;

How to use Database

In MySQL database, you need to select a database first before executing any query on table, view
etc. To do so, we use following query:

USE DATABASE database_name;

What is Table:

Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.

Note: A table has a specified number of columns, but can have any number of rows.

Table is the simple form of data storage. A table is also considered as a convenient representation of
relations.

Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY


Ankit Lucknow 15000
Raman Allahabad 18000
Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY"
are the column names. The combination of data of multiple columns forms a row e.g. "Ankit",
"Lucknow" and 15000 are the data of one row.

Degree of a table: No. of columns


Cardinality of a table: No. of distinct rows in a table
If we want to create a table, we should name the table and define its column and each column's data
type.

Let's see the simple syntax to create the table.

create table "tablename"


("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");

The data type of the columns may vary from one database to another. For example, NUMBER is
supported in Oracle database for integer value whereas INT is supported in MySQL.

Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL are
the constraint showing that these fields cannot be NULL while creating records in the table.

SQL> CREATE TABLE STUDENTS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
);

You can verify it, if you have created the table successfully by looking at the message displayed by
the SQL Server, else you can use DESCRIBE command as follows:

SQL> DESCRIBE STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA


ID Int(11) NO PRI
NAMEVarchar(20) NO
AGE Int(11) NO
ADDRESS Varchar(25) YES NULL

SQL to delete TABLE:


DROP TABLE statement is used to delete a table definition and all data from a table.

This is very important to know that once a table is deleted all the information available in the table
is lost forever, so we have to be very careful when using this command.

Let's see the syntax to drop the table from the database.

SQL> DROP TABLE table_name;

SQL> DESC STUDENTS;


ALTER TABLE

The ALTER TABLE statement is used to add, modify or delete columns in an existing table. It is
also used to rename a table.

We can also use ALTER TABLE command to add and drop various constraints on an existing table.

If we want to add columns in SQL table, the SQL alter table syntax is given below:

SQL>ALTER TABLE table_name ADD column_name column-definition;

If we want to add multiple columns in table, the SQL table will be

SQL> ALTER TABLE table_name


ADD (column_1 column-definition,
column_2 column-definition,
.....
column_n column-definition);

If we want to modify an existing column in SQL table, syntax is given below:

SQL>ALTER TABLE table_name MODIFY column_name column_type;

If we want to modify multiple columns in table, the SQL table will be

SQL>ALTER TABLE table_name


MODIFY (column_1 column_type,
column_2 column_type,
.....
column_n column_type);

The syntax of alter table drop column is given below:

SQL>ALTER TABLE table_name DROP COLUMN column_name;

The syntax of alter table rename column is given below

mysql> alter table tablename change column oldfieldname newfieldname datatype;

To rename table
mysql> RENAME TABLE old_tab1 TO new_tab1;

To rename multiple tables


mysql> RENAME TABLE old_tab1 TO new_tab1, old_tab2 TO new_tab2;

To rename clolumns
mysql> ALTER TABLE table_name
CHANGE old_column_name1 new_column_name1 Data Type,
CHANGE old_column_name2 new_column_name2 Data Type;

To add Primary key on one column:


When table is already created and wewant to create a PRIMARY KEY constraint on the ?S_Id?
column you should use the following SQL:

SQL> ALTER TABLE students


ADD PRIMARY KEY (S_Id)

Primary key on multiple column:

ALTER TABLE students


ADD CONSTRAINT pk_StudentID PRIMARY KEY (S_Id,LastName)

When we use ALTER TABLE statement to add a primary key, the primary key columns must not
contain NULL values (when the table was first created).

How to DROP a PRIMARY KEY constraint?

If we want to DROP (remove) a primary key constraint, we should use following syntax:

SQL> ALTER TABLE students DROP PRIMARY KEY


SQL FOREIGN KEY constraint for ALTER TABLE:

If the Order table is already created and you want to create a FOREIGN KEY constraint on the
?S_Id? column, you should write the following syntax:

Defining a foreign key constraint on single column:

ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY(S_Id)


REFERENCES Students (S_Id)

DROP SYNTAX for FOREIGN KEY COSTRAINT:

If you want to drop a FOREIGN KEY constraint, use the following syntax:

MySQL:

ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders


Difference between primary key and foreign key in SQL:

These are some important difference between primary key and foreign key in SQL-

Primary key cannot be null on the other hand foreign key can be null.

Primary key is always unique while foreign key can be duplicated.

Primary key uniquely identify a record in a table while foreign key is a field in a table that is
primary key in another table.

There is only one primary key in the table on the other hand we can have more than one foreign key
in the table.

composite key:
It is a combination of two or more columns in a table that can be used to uniquely identify each
row in the table when the columns are combined uniqueness is guaranteed, but when it taken
individually it does not guarantee uniqueness.

Sometimes more than one attributes are needed to uniquely identify an entity. A primary key that is
made by the combination of more than one attribute is known as a composite key.

In other words we can say that:

Composite key is a key which is the combination of more than one field or column of a given table.
It may be a candidate key or primary key.

Columns that make up the composite key can be of different data types.

SQL Syntax to specify composite key:

CREATE TABLE TABLE_NAME


(COLUMN_1, DATA_TYPE_1,
COLUMN_2, DATA_TYPE_2,
???
PRIMARY KEY (COLUMN_1, COLUMN_2, ...));

In all cases composite key created consist of COLUMN1 and COLUMN2.

MySQL:

CREATE TABLE SAMPLE_TABLE


(COL1 integer,
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));

Unique Key in SQL

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a
record in a database table.

You can say that it is little like primary key but it can accept only one null value and it cannot have
duplicate values.

The unique key and primary key both provide a guarantee for uniqueness for a column or a set of
columns.

There is an automatically defined unique key constraint within a primary key constraint.

There may be many unique key constraints for one table, but only one PRIMARY KEY constraint
for one table.

UNIQUE KEY
We want to create a UNIQUE constraint on the ?S_Id? column when the ?students? table is created,
use the following SQL syntax:

CREATE TABLE students


(
S_Id int NOT NULL, LastName varchar (255) NOT NULL, FirstName varchar (255),
City varchar (255), UNIQUE (S_Id) );

(Defining a unique key constraint on multiple columns):

CREATE TABLE students


(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
CONSTRAINT uc_studentId UNIQUE (S_Id, LastName)
)

(Defining a unique key constraint on single column):

ALTER TABLE students


ADD UNIQUE (S_Id)

If we want to drop a UNIQUE constraint, use the following SQL syntax:

SQL> ALTER TABLE students


DROP INDEX uc_studentID

Alternate Key in SQL:


Alternate key is a secondary key it can be simple to understand by an example:

Let's take an example of student it can contain NAME, ROLL NO., ID and CLASS.

Here ROLL NO. is primary key and rest of all columns like ID is alternate key.

If a table has more than one candidate key, one of them will become the primary key and rest of all
are called alternate keys.

In simple words, you can say that any of the candidate key which is not part of primary key is called
an alternate key. So when we talk about alternate key, the column may not be primary key but still it
is a unique key in the column.
An alternate key is just a candidate key that has not been selected as the primary key.

Add not null constraint by Alter

Alter table table name modify column name new data type and constraint

mysql> alter table emp modify name varchar(40) not null;

Select Statements:

+--------+------------------------------+-----------+-----------+----------------+--------------+------------+
| pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd
|
+--------+------------------------------+-----------+-----------+----------------+--------------+------------+
| P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-
25 |
| P002 | BPP Publication | Mumbai | India | New Delhi | 10 | 1985-10-01 |
| P003 | New Harrold Publication | Adelaide | Australia | Sydney | 6 | 1975-09-
05 |
| P004 | Ultra Press Inc. | London | UK | London | 8 | 1948-07-10 |
| P005 | Mountain Publication | Houstan | USA | Sun Diego | 25 | 1975-01-01
|
| P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-
10 |
| P007 | Pieterson Grp. of Publishers | Cambridge | UK | London | 6 | 1950-07-
15 |
| P008 | Novel Publisher Ltd. | New Delhi | India | Bangalore | 10 | 2000-01-01
|
+--------+------------------------------+-----------+-----------+----------------+--------------+------------+

SELECT statement is used to fetch rows or records from one or more tables.

MySQL SELECT statement without any condition retrieves all records from a table. The following
SELECT statement will retrieve all data from publisher table.
SELECT *
FROM publisher;

mysql> SELECT * FROM publisher;


+--------+------------------------------+-----------+-----------+----------------+--------------+------------+
| pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd |
+--------+------------------------------+-----------+-----------+----------------+--------------+------------+
| P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 |
| P002 | BPP Publication | Mumbai | India | New Delhi | 10 | 1985-10-01 |
| P003 | New Harrold Publication | Adelaide | Australia | Sydney | 6 | 1975-09-05 |
| P004 | Ultra Press Inc. | London | UK | London | 8 | 1948-07-10 |
| P005 | Mountain Publication | Houstan | USA | Sun Diego | 25 | 1975-01-01 |
| P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 |
| P007 | Pieterson Grp. of Publishers | Cambridge | UK | London | 6 | 1950-07-15 |
| P008 | Novel Publisher Ltd. | New Delhi | India | Bangalore | 10 | 2000-01-01 |
+--------+------------------------------+-----------+-----------+----------------+--------------+------------+
8 rows in set (0.00 sec)

This following SELECT statement will retrieve those particular rows where 'country' is the
USA.

SELECT *
FROM publisher
WHERE country='USA'

+--------+--------------------------+----------+---------+----------------+--------------+------------+
| pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd |
+--------+--------------------------+----------+---------+----------------+--------------+------------+
| P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 |
| P005 | Mountain Publication | Houstan | USA | Sun Diego | 25 | 1975-01-01 |
| P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 |
+--------+--------------------------+----------+---------+----------------+--------------+------------+
3 rows in set (0.01 sec)

MySQL SELECT specific rows with AND operator

MySQL AND operator is used to combine more than one conditions aiming to fetch records when
both of the conditions are satisfied. The following SELECT statement will retrieve those particular
rows where country and city of the publisher are 'USA' and 'New York'.

mysql> SELECT * FROM publisher


-> WHERE country='USA'
-> AND pub_city='New York';
+--------+--------------------------+----------+---------+----------------+--------------+------------+
| pub_id | pub_name | pub_city | country | country_office | no_of_branch | estd |
+--------+--------------------------+----------+---------+----------------+--------------+------------+
| P001 | Jex Max Publication | New York | USA | New York | 15 | 1969-12-25 |
| P006 | Summer Night Publication | New York | USA | Atlanta | 10 | 1990-12-10 |
+--------+--------------------------+----------+---------+----------------+--------------+------------+
2 rows in set (0.00 sec)
MySQL SELECT specific columns

To retrieve records from specific columns, you need to specify a list of comma separated columns.
The following MySQL statement returns the name of the book, author id, and price of the books
from book_mast table.
+---------+-------------------------------------+-------------+---------+--------+--------+------------+----------
+---------+------------+
| book_id | book_name | isbn_no | cate_id | aut_id | pub_id | dt_of_pub |
pub_lang | no_page | book_price |
+---------+-------------------------------------+-------------+---------+--------+--------+------------+----------
+---------+------------+
| BK001 | Introduction to Electrodynamics | 0000979001 | CA001 | AUT001 | P003 | 2001-
05-08 | English | 201 | 85.00 |
| BK002 | Understanding of Steel Construction | 0000979002 | CA002 | AUT002 | P001 | 2003-
07-15 | English | 300 | 105.50 |
| BK003 | Guide to Networking | 0000979003 | CA003 | AUT003 | P002 | 2002-09-10
| Hindi | 510 | 200.00 |
| BK004 | Transfer of Heat and Mass | 0000979004 | CA002 | AUT004 | P004 | 2004-02-
16 | English | 600 | 250.00 |
| BK005 | Conceptual Physics | 0000979005 | CA001 | AUT005 | P006 | 2003-07-16 |
NULL | 345 | 145.00 |
| BK006 | Fundamentals of Heat | 0000979006 | CA001 | AUT006 | P005 | 2003-08-10
| German | 247 | 112.00 |
| BK007 | Advanced 3d Graphics | 0000979007 | CA003 | AUT007 | P002 | 2004-02-
16 | Hindi | 165 | 56.00 |
| BK008 | Human Anatomy | 0000979008 | CA005 | AUT008 | P006 | 2001-05-17
| German | 88 | 50.50 |
| BK009 | Mental Health Nursing | 0000979009 | CA005 | AUT009 | P007 | 2004-02-10
| English | 350 | 145.00 |
| BK010 | Fundamentals of Thermodynamics | 0000979010 | CA002 | AUT010 | P007 |
2002-10-14 | English | 400 | 225.00 |
| BK011 | The Experimental Analysis of Cat | 0000979011 | CA004 | AUT011 | P005 | 2007-
06-09 | French | 225 | 95.00 |
| BK012 | The Nature of World | 0000979012 | CA004 | AUT005 | P008 | 2005-12-20 |
English | 350 | 88.00 |
| BK013 | Environment a Sustainable Future | 0000979013 | CA004 | AUT012 | P001 | 2003-
10-27 | German | 165 | 100.00 |
| BK014 | Concepts in Health | 0000979014 | CA005 | AUT013 | P004 | 2001-08-25 |
NULL | 320 | 180.00 |
| BK015 | Anatomy & Physiology | 0000979015 | CA005 | AUT014 | P008 | 2000-10-
10 | Hindi | 225 | 135.00 |
| BK016 | Networks and Telecommunications | 00009790_16 | CA003 | AUT015 | P003 |
2002-01-01 | French | 95 | 45.00 |
mysql> SELECT book_name,aut_id,book_price
-> FROM book_mast;
+-------------------------------------+--------+------------+
| book_name | aut_id | book_price |
+-------------------------------------+--------+------------+
| Introduction to Electrodynamics | AUT001 | 85.00 |
| Understanding of Steel Construction | AUT002 | 105.50 |
| Guide to Networking | AUT003 | 200.00 |
| Transfer of Heat and Mass | AUT004 | 250.00 |
| Conceptual Physics | AUT005 | 145.00 |
| Fundamentals of Heat | AUT006 | 112.00 |
| Advanced 3d Graphics | AUT007 | 56.00 |
| Human Anatomy | AUT008 | 50.50 |
| Mental Health Nursing | AUT009 | 145.00 |
| Fundamentals of Thermodynamics | AUT010 | 225.00 |
| The Experimental Analysis of Cat | AUT011 | 95.00 |
| The Nature of World | AUT005 | 88.00 |
| Environment a Sustainable Future | AUT012 | 100.00 |
| Concepts in Health | AUT013 | 180.00 |
| Anatomy & Physiology | AUT014 | 135.00 |
| Networks and Telecommunications | AUT015 | 45.00 |
+-------------------------------------+--------+------------+
16 rows in set (0.01 sec)

MySQL select specific columns with distinct operator

DISTINCT clause is used to retrieve unique rows from a table. The following MySQL statement
retrieves the unique author ids from book_mast table.

mysql> SELECT DISTINCT aut_id


-> FROM book_mast;
+--------+
| aut_id |
+--------+
| AUT001 |
| AUT002 |
| AUT003 |
| AUT004 |
| AUT005 |
| AUT006 |
| AUT007 |
| AUT008 |
| AUT009 |
| AUT010 |
| AUT011 |
| AUT012 |
| AUT013 |
| AUT014 |
| AUT015 |
+--------+
15 rows in set (0.01 sec)

MySQL sorting rows in ascending order

MySQL ORDER BY clause specifies the order in which columns are sorted while retrieving data in
a SELECT statement. By default, columns are sorted in ascending order. You can use ASC keyword
to achieve the same result.

Note : In the case of character type column sorting the sorting is dependent upon case sensitivity.
The default sort order is ascending this means smallest value comes first. To sort in reverse order,
DESC key has to be used.

In the following MySQL statement, all records of pub_name, country and pub_city columns of
publisher table are being fetched and sorted against pub_name column. Since we have not specified
any order keyword (ASC or DESC), by default, it is sorted in ascending order.

mysql> SELECT pub_name,country,pub_city


-> FROM publisher
-> ORDER BY pub_name;
+------------------------------+-----------+-----------+
| pub_name | country | pub_city |
+------------------------------+-----------+-----------+
| BPP Publication | India | Mumbai |
| Jex Max Publication | USA | New York |
| Mountain Publication | USA | Houstan |
| New Harrold Publication | Australia | Adelaide |
| Novel Publisher Ltd. | India | New Delhi |
| Pieterson Grp. of Publishers | UK | Cambridge |
| Summer Night Publication | USA | New York |
| Ultra Press Inc. | UK | London |
+------------------------------+-----------+-----------+
8 rows in set (0.02 sec)

MySQL sorting rows in descending order

The following MySQL statement sort rows of a table in descending order using ORDER BY clause.

mysql> SELECT pub_name,country,pub_city


-> FROM publisher
-> ORDER BY pub_name DESC;
+------------------------------+-----------+-----------+
| pub_name | country | pub_city |
+------------------------------+-----------+-----------+
| Ultra Press Inc. | UK | London |
| Summer Night Publication | USA | New York |
| Pieterson Grp. of Publishers | UK | Cambridge |
| Novel Publisher Ltd. | India | New Delhi |
| New Harrold Publication | Australia | Adelaide |
| Mountain Publication | USA | Houstan |
| Jex Max Publication | USA | New York |
| BPP Publication | India | Mumbai |
+------------------------------+-----------+-----------+
8 rows in set (0.00 sec)

MySQL sorting rows on multiple columns

Sort can be performed on multiple columns. The way this type of sort happen is, firstly the rows
will be sorted on the first column then the rows will be sorted on the second column whose first
column's data are same.

In the following MySQL statement, all records of pub_name, country and pub_city columns of
publisher table are being fetched and sorted against country and pub_city columns. Since we have
not specified any order keyword (ASC or DESC), by default, it is sorted in ascending order.

mysql> SELECT pub_name, country, pub_city


-> FROM publisher
-> ORDER BY country, pub_city;

+------------------------------+-----------+-----------+
| pub_name | country | pub_city |
+------------------------------+-----------+-----------+
| New Harrold Publication | Australia | Adelaide |
| BPP Publication | India | Mumbai |
| Novel Publisher Ltd. | India | New Delhi |
| Pieterson Grp. of Publishers | UK | Cambridge |
| Ultra Press Inc. | UK | London |
| Mountain Publication | USA | Houstan |
| Jex Max Publication | USA | New York |
| Summer Night Publication | USA | New York |
+------------------------------+-----------+-----------+
8 rows in set (0.00 sec)

UNION

In MySQL, the UNION operator is used to combine the result from multiple SELECT statements
into a single result set.

The default characteristic of UNION is, to remove the duplicate rows from the result. The
DISTINCT keyword which is optional does not make any effect, because, by default, it specifies
duplicate-row removal. But if we use the optional keyword ALL, the duplicate-row removal does
not happen and the result set includes all matching rows from all the SELECT statements.

Employees:
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL
PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT
MANAGER_ID DEPARTMENT_ID
100 Steven King SKING 515.123.4567 17-Jun-87 AD_PRES 24000
90
101 Neena Kochhar NKOCHHAR 515.123.4568 21-Sep-89 AD_VP
17000 100 90
102 Lex De Haan LDEHAAN 515.123.4569 13-Jan-93 AD_VP 17000
100 90
103 Alexander Hunold AHUNOLD 590.423.4567 3-Jan-90 IT_PROG
9000 102 60
104 Bruce Ernst BERNST 590.423.4568 21-May-91 IT_PROG 6000 103
60
105 David Austin DAUSTIN 590.423.4569 25-Jun-97 IT_PROG 4800 103
60
106 Valli Pataballa VPATABAL 590.423.4560 5-Feb-98 IT_PROG 4800
103 60
107 Diana Lorentz DLORENTZ 590.423.5567 7-Feb-99 IT_PROG 4200
103 60
108 Nancy Greenberg NGREENBE 515.124.4569 17-Aug-94 FI_MGR 12000
101 100
109 Daniel Faviet DFAVIET 515.124.4169 16-Aug-94 FI_ACCOUNT 9000
108 100
110 John Chen JCHEN 515.124.4269 28-Sep-97 FI_ACCOUNT 8200
108 100
111 Ismael Sciarra ISCIARRA 515.124.4369 30-Sep-97 FI_ACCOUNT
7700 108 100
112 Jose Manuel Urman JMURMAN 515.124.4469 7-Mar-98 FI_ACCOUNT
7800 108 100
113 Luis Popp LPOPP 515.124.4567 7-Dec-99 FI_ACCOUNT 6900
108 100
114 Den Raphaely DRAPHEAL 515.127.4561 7-Dec-94 PU_MAN 11000
100 30
115 Alexander Khoo AKHOO 515.127.4562 18-May-95 PU_CLERK 3100
114 30
116 Shelli Baida SBAIDA 515.127.4563 24-Dec-97 PU_CLERK 2900 114
30
117 Sigal Tobias STOBIAS 515.127.4564 24-Jul-97 PU_CLERK 2800 114
30
118 Guy Himuro GHIMURO 515.127.4565 15-Nov-98 PU_CLERK 2600
114 30
119 Karen Colmenares KCOLMENA 515.127.4566 10-Aug-99 PU_CLERK 2500
114 30
120 Matthew Weiss MWEISS 650.123.1234 18-Jul-96 ST_MAN 8000
100 50
121 Adam Fripp AFRIPP 650.123.2234 10-Apr-97 ST_MAN 8200 100
50
122 Payam Kaufling PKAUFLIN 650.123.3234 1-May-95 ST_MAN
7900 100 50
123 Shanta Vollman SVOLLMAN 650.123.4234 10-Oct-97 ST_MAN
6500 100 50
124 Kevin Mourgos KMOURGOS 650.123.5234 16-Nov-99 ST_MAN
5800 100 50
125 Julia Nayer JNAYER 650.124.1214 16-Jul-97 ST_CLERK 3200 120
50
126 Irene Mikkilineni IMIKKILI 650.124.1224 28-Sep-98 ST_CLERK 2700
120 50
127 James Landry JLANDRY 650.124.1334 14-Jan-99 ST_CLERK 2400
120 50
128 Steven Markle SMARKLE 650.124.1434 8-Mar-00 ST_CLERK
2200 120 50
129 Laura Bissot LBISSOT 650.124.5234 20-Aug-97 ST_CLERK 3300 121
50
130 Mozhe Atkinson MATKINSO 650.124.6234 30-Oct-97 ST_CLERK
2800 121 50
131 James Marlow JAMRLOW 650.124.7234 16-Feb-97 ST_CLERK 2500
121 50
132 TJ Olson TJOLSON 650.124.8234 10-Apr-99 ST_CLERK 2100 121
50
133 Jason Mallin JMALLIN 650.127.1934 14-Jun-96 ST_CLERK 3300 122
50
134 Michael Rogers MROGERS 650.127.1834 26-Aug-98 ST_CLERK
2900 122 50
135 Ki Gee KGEE 650.127.1734 12-Dec-99 ST_CLERK 2400 122 50
136 Hazel Philtanker HPHILTAN 650.127.1634 6-Feb-00 ST_CLERK 2200
122 50
137 Renske Ladwig RLADWIG 650.121.1234 14-Jul-95 ST_CLERK
3600 123 50
138 Stephen Stiles SSTILES 650.121.2034 26-Oct-97 ST_CLERK 3200
123 50
139 John Seo JSEO 650.121.2019 12-Feb-98 ST_CLERK 2700 123 50
140 Joshua Patel JPATEL 650.121.1834 6-Apr-98 ST_CLERK 2500
123 50
141 Trenna Rajs TRAJS 650.121.8009 17-Oct-95 ST_CLERK 3500
124 50
142 Curtis Davies CDAVIES 650.121.2994 29-Jan-97 ST_CLERK 3100
124 50
143 Randall Matos RMATOS 650.121.2874 15-Mar-98 ST_CLERK 2600
124 50
144 Peter Vargas PVARGAS 650.121.2004 9-Jul-98 ST_CLERK 2500 124
50
145 John Russell JRUSSEL 011.44.1344.429268 1-Oct-96 SA_MAN
14000 0.4 100 80
146 Karen Partners KPARTNER 011.44.1344.467268 5-Jan-97 SA_MAN
13500 0.3 100 80
147 Alberto Errazuriz AERRAZUR 011.44.1344.429278 10-Mar-97 SA_MAN
12000 0.3 100 80
148 Gerald Cambrault GCAMBRAU 011.44.1344.619268 15-Oct-99
SA_MAN 11000 0.3 100 80
149 Eleni Zlotkey EZLOTKEY 011.44.1344.429018 29-Jan-00 SA_MAN
10500 0.2 100 80
150 Peter Tucker PTUCKER 011.44.1344.129268 30-Jan-97 SA_REP
10000 0.3 145 80
151 David Bernstein DBERNSTE 011.44.1344.345268 24-Mar-97 SA_REP
9500 0.25 145 80
152 Peter Hall PHALL 011.44.1344.478968 20-Aug-97 SA_REP 9000 0.25
145 80
153 Christopher Olsen COLSEN 011.44.1344.498718 30-Mar-98 SA_REP
8000 0.2 145 80
154 Nanette Cambrault NCAMBRAU 011.44.1344.987668 9-Dec-98
SA_REP 7500 0.2 145 80
155 Oliver Tuvault OTUVAULT 011.44.1344.486508 23-Nov-99 SA_REP
7000 0.15 145 80
156 Janette King JKING 011.44.1345.429268 30-Jan-96 SA_REP
10000 0.35 146 80
157 Patrick Sully PSULLY 011.44.1345.929268 4-Mar-96 SA_REP
9500 0.35 146 80
158 Allan McEwen AMCEWEN 011.44.1345.829268 1-Aug-96 SA_REP
9000 0.35 146 80
159 Lindsey Smith LSMITH 011.44.1345.729268 10-Mar-97 SA_REP
8000 0.3 146 80
160 Louise Doran LDORAN 011.44.1345.629268 15-Dec-97 SA_REP
7500 0.3 146 80
161 Sarath Sewall SSEWALL 011.44.1345.529268 3-Nov-98 SA_REP
7000 0.25 146 80
162 Clara Vishney CVISHNEY 011.44.1346.129268 11-Nov-97 SA_REP
10500 0.25 147 80
163 Danielle Greene DGREENE 011.44.1346.229268 19-Mar-99 SA_REP
9500 0.15 147 80
164 Mattea Marvins MMARVINS 011.44.1346.329268 24-Jan-00 SA_REP
7200 0.1 147 80
165 David Lee DLEE 011.44.1346.529268 23-Feb-00 SA_REP 6800 0.1 147
80
166 Sundar Ande SANDE 011.44.1346.629268 24-Mar-00 SA_REP
6400 0.1 147 80
167 Amit Banda ABANDA 011.44.1346.729268 21-Apr-00 SA_REP 6200 0.1
147 80
168 Lisa Ozer LOZER 011.44.1343.929268 11-Mar-97 SA_REP 11500 0.25
148 80
169 Harrison Bloom HBLOOM 011.44.1343.829268 23-Mar-98 SA_REP
10000 0.2 148 80
170 Tayler Fox TFOX 011.44.1343.729268 24-Jan-98 SA_REP 9600 0.2 148
80
171 William Smith WSMITH 011.44.1343.629268 23-Feb-99 SA_REP
7400 0.15 148 80
172 Elizabeth Bates EBATES 011.44.1343.529268 24-Mar-99 SA_REP
7300 0.15 148 80
173 Sundita Kumar SKUMAR 011.44.1343.329268 21-Apr-00 SA_REP
6100 0.1 148 80
174 Ellen Abel EABEL 011.44.1644.429267 11-May-96 SA_REP 11000 0.3
149 80
175 Alyssa Hutton AHUTTON 011.44.1644.429266 19-Mar-97 SA_REP
8800 0.25 149 80
176 Jonathon Taylor JTAYLOR 011.44.1644.429265 24-Mar-98 SA_REP
8600 0.2 149 80
177 Jack Livingston JLIVINGS 011.44.1644.429264 23-Apr-98 SA_REP
8400 0.2 149 80
178 Kimberely Grant KGRANT 011.44.1644.429263 24-May-99 SA_REP
7000 0.15 149
179 Charles Johnson CJOHNSON 011.44.1644.429262 4-Jan-00 SA_REP
6200 0.1 149 80
180 Winston Taylor WTAYLOR 650.507.9876 24-Jan-98 SH_CLERK 3200
120 50
181 Jean Fleaur JFLEAUR 650.507.9877 23-Feb-98 SH_CLERK 3100 120
50
182 Martha Sullivan MSULLIVA 650.507.9878 21-Jun-99 SH_CLERK
2500 120 50
183 Girard Geoni GGEONI 650.507.9879 3-Feb-00 SH_CLERK 2800 120
50
184 Nandita Sarchand NSARCHAN 650.509.1876 27-Jan-96 SH_CLERK
4200 121 50
185 Alexis Bull ABULL 650.509.2876 20-Feb-97 SH_CLERK 4100 121
50
186 Julia Dellinger JDELLING 650.509.3876 24-Jun-98 SH_CLERK 3400
121 50
187 Anthony Cabrio ACABRIO 650.509.4876 7-Feb-99 SH_CLERK
3000 121 50
188 Kelly Chung KCHUNG 650.505.1876 14-Jun-97 SH_CLERK 3800 122
50
189 Jennifer Dilly JDILLY 650.505.2876 13-Aug-97 SH_CLERK 3600
122 50
190 Timothy Gates TGATES 650.505.3876 11-Jul-98 SH_CLERK 2900
122 50
191 Randall Perkins RPERKINS 650.505.4876 19-Dec-99 SH_CLERK
2500 122 50
192 Sarah Bell SBELL 650.501.1876 4-Feb-96 SH_CLERK 4000 123
50
193 Britney Everett BEVERETT 650.501.2876 3-Mar-97 SH_CLERK
3900 123 50
194 Samuel McCain SMCCAIN 650.501.3876 1-Jul-98 SH_CLERK
3200 123 50
195 Vance Jones VJONES 650.501.4876 17-Mar-99 SH_CLERK 2800 123
50
196 Alana Walsh AWALSH 650.507.9811 24-Apr-98 SH_CLERK 3100 124
50
197 Kevin Feeney KFEENEY 650.507.9822 23-May-98 SH_CLERK 3000
124 50
198 Donald OConnell DOCONNEL 650.507.9833 21-Jun-99 SH_CLERK
2600 124 50
199 Douglas Grant DGRANT 650.507.9844 13-Jan-00 SH_CLERK 2600
124 50
200 Jennifer Whalen JWHALEN 515.123.4444 17-Sep-87 AD_ASST
4400 101 10
201 Michael Hartstein MHARTSTE 515.123.5555 17-Feb-96 MK_MAN
13000 100 20
202 Pat Fay PFAY 603.123.6666 17-Aug-97 MK_REP 6000 201 20
203 Susan Mavris SMAVRIS 515.123.7777 7-Jun-94 HR_REP 6500
101 40
204 Hermann Baer HBAER 515.123.8888 7-Jun-94 PR_REP 10000
101 70
205 Shelley Higgins SHIGGINS 515.123.8080 7-Jun-94 AC_MGR
12000 101 110
206 William Gietz WGIETZ 515.123.8181 7-Jun-94 AC_ACCOUNT
8300 205 110

job_history:

EMPLOYEE_ID START_DATE END_DATE JOB_ID DEPARTMENT_ID


102 13-Jan-93 24-Jul-98 IT_PROG 60
101 21-Sep-89 27-Oct-93 AC_ACCOUNT 110
101 28-Oct-93 15-Mar-97 AC_MGR 110
201 17-Feb-96 19-Dec-99 MK_REP 20
114 24-Mar-98 31-Dec-99 ST_CLERK 50
122 1-Jan-99 31-Dec-99 ST_CLERK 50
200 17-Sep-87 17-Jun-93 AD_ASST 90
176 24-Mar-98 31-Dec-98 SA_REP 80
176 1-Jan-99 31-Dec-99 SA_MAN 80
200 1-Jul-94 31-Dec-98 AC_ACCOUNT 90

Select employee_id, job_id


FROM employees
UNION
Select employee_id,job_id
FROM job_history;

employee_id | job_id |
+-------------+------------+
| 100 | AD_PRES |
| 101 | AD_VP |
| 102 | AD_VP |
| 103 | IT_PROG |
| 104 | IT_PROG |
| 105 | IT_PROG |
| 106 | IT_PROG |
| 107 | IT_PROG |
| 108 | FI_MGR |
| 109 | FI_ACCOUNT |
| 110 | FI_ACCOUNT |
| 111 | FI_ACCOUNT |
| 112 | FI_ACCOUNT |
| 113 | FI_ACCOUNT |
| 114 | PU_MAN |
| 115 | PU_CLERK |
| 116 | PU_CLERK |
| 117 | PU_CLERK |
| 118 | PU_CLERK |
| 119 | PU_CLERK |
| 120 | ST_MAN |
| 121 | ST_MAN |
| 122 | ST_MAN |
| 123 | ST_MAN |
| 124 | ST_MAN |
| 125 | ST_CLERK |
| 126 | ST_CLERK |
| 127 | ST_CLERK |
| 128 | ST_CLERK |
| 129 | ST_CLERK |
| 130 | ST_CLERK |
| 131 | ST_CLERK |
| 132 | ST_CLERK |
| 133 | ST_CLERK |
| 134 | ST_CLERK |
| 135 | ST_CLERK

MySQL UNION ALL

The UNION ALL operator does not eliminate duplicate selected rows and returns all rows.

Pictorial presentation of UNION ALL operator

The UNION ALL operator returns all the rows from both the queries and no duplication elimination
happens.

Select employee_id, job_id,department_id


FROM employees
UNION ALL
Select employee_id,job_id,department_id
FROM job_history;

MySQL UNION ORDER BY

The ORDER BY clause with UNION arrange the rows in the result set in a specific order. The
default order is ascending. The ORDER BY only used at the very end of the statement.

SELECT employee_id, job_id


FROM employees
UNION
SELECT employee_id,job_id
FROM job_history
ORDER BY employee_id;

aggregate functions
MySQL aggregate functions retrieve a single value after performing a calculation on a set of values.

In general, aggregate functions ignore null values.


Often, aggregate functions are accompanied by the GROUP BY clause of the SELECT statement.

book_id | book_name | isbn_no | cate_id | aut_id | pub_id | dt_of_pub | pub_lang


| no_page | book_price |
+---------+-------------------------------------+-------------+---------+--------+--------+------------+----------
+---------+------------+
| BK001 | Introduction to Electrodynamics | 0000979001 | CA001 | AUT001 | P003 | 2001-
05-08 | English | 201 | 85.00 |
| BK002 | Understanding of Steel Construction | 0000979002 | CA002 | AUT002 | P001 | 2003-
07-15 | English | 300 | 105.50 |
| BK003 | Guide to Networking | 0000979003 | CA003 | AUT003 | P002 | 2002-09-10
| Hindi | 510 | 200.00 |
| BK004 | Transfer of Heat and Mass | 0000979004 | CA002 | AUT004 | P004 | 2004-02-
16 | English | 600 | 250.00 |
| BK005 | Conceptual Physics | 0000979005 | CA001 | AUT005 | P006 | 2003-07-16 |
NULL | 345 | 145.00 |
| BK006 | Fundamentals of Heat | 0000979006 | CA001 | AUT006 | P005 | 2003-08-10
| German | 247 | 112.00 |
| BK007 | Advanced 3d Graphics | 0000979007 | CA003 | AUT007 | P002 | 2004-02-
16 | Hindi | 165 | 56.00 |
| BK008 | Human Anatomy | 0000979008 | CA005 | AUT008 | P006 | 2001-05-17
| German | 88 | 50.50 |
| BK009 | Mental Health Nursing | 0000979009 | CA005 | AUT009 | P007 | 2004-02-10
| English | 350 | 145.00 |
| BK010 | Fundamentals of Thermodynamics | 0000979010 | CA002 | AUT010 | P007 |
2002-10-14 | English | 400 | 225.00 |
... ... ...

mysql> SELECT AVG(no_page) FROM book_mast;


+--------------+
| AVG(no_page) |
+--------------+
| 286.6250 |
+--------------+

1 row in set (0.02 sec)

MySQL AVG() function with group by

MySQL AVG() function retrieves the average value of a given expression for each group if it is
used with group by option. The following statement will return the average number of pages for
each group of 'pub_id'

mysql> SELECT pub_id, AVG(no_page)


-> FROM book_mast
-> GROUP BY pub_id;
+--------+--------------+
| pub_id | AVG(no_page) |
+--------+--------------+
| P001 | 232.5000 |
| P002 | 337.5000 |
| P003 | 148.0000 |
| P004 | 460.0000 |
| P005 | 236.0000 |
| P006 | 216.5000 |
| P007 | 375.0000 |
| P008 | 287.5000 |
+--------+--------------+
8 rows in set (0.02 sec)

Purchase

book_name | pub_lang | cate_id | receive_qty | purch_price | total_cost |


+------------+------------+----------------+------------+------------+---------+---------------------------------+-
---------+---------+-------------+-------------+------------+
| INV0001 | 2008-07-15 | ORD/08-09/0001 | 2008-07-06 | 2008-07-19 | BK001 | Introduction to
Electrodynamics | English | CA001 | 15 | 75.00 | 1125.00 |
| INV0002 | 2008-08-25 | ORD/08-09/0002 | 2008-08-09 | 2008-08-28 | BK004 | Transfer of
Heat and Mass | English | CA002 | 8| 55.00 | 440.00 |
| INV0003 | 2008-09-20 | ORD/08-09/0003 | 2008-09-15 | 2008-09-23 | BK005 | Conceptual
Physics | NULL | CA001 | 20 | 20.00 | 400.00 |
| INV0004 | 2007-08-30 | ORD/07-08/0005 | 2007-08-22 | 2007-08-30 | BK004 | Transfer of
Heat and Mass | English | CA002 | 15 | 35.00 | 525.00 |
| INV0005 | 2007-07-28 | ORD/07-08/0004 | 2007-06-25 | 2007-07-30 | BK001 | Introduction to
Electrodynamics | English | CA001 | 8| 25.00 | 200.00 |
| INV0006 | 2007-09-24 | ORD/07-08/0007 | 2007-09-20 | 2007-09-30 | BK003 | Guide to
Networking | Hindi | CA003 | 20 | 45.00 | 900.00

mysql> SELECT AVG(DISTINCT(receive_qty))


-> FROM purchase;
+----------------------------+
| AVG(DISTINCT(receive_qty)) |
+----------------------------+
| 14.3333 |
+----------------------------+
1 row in set (0.02 sec)

Similarly MIN( ), MAX( ), SUM( ), COUNT( ), STDDEV( ), VARIANCE( )

Difference between COUNT( ) and COUNT(*)

SELECT can also be used to retrieve rows computed without reference to any table.

mysql> SELECT 5 - 3 ;
+-------+
|5-3|
+-------+
| 2|
+-------+
We can specify DUAL as a dummy table name where no tables are referenced :

mysql> SELECT 5 - 3 FROM DUAL;


+-------+
|5-3|
+-------+
| 2|
+-------+
1 row in set (0.00 sec)

MySQL Joins :

INNER JOIN
LEFT JOIN
RIGHT JOIN
CROSS JOIN

Here is the sample tables table_A and table_B, which we have used to explain the technologies
behind the joins.

sample table for inner join

MySQL INNER JOIN

The INNER JOIN is such a JOIN in which all rows can be selected from both participating tables as
long as there is a match between the columns. Usage of INNER JOIN combines the tables. An
INNER JOIN allows rows from either table to appear in the result if and only if both tables meet the
conditions specified in the ON clause.

Example
view plaincopy to clipboardprint?

SELECT * FROM table_A


INNER JOIN table_B
ON table_A.A=table_B.A;

MySQL LEFT JOIN

The LEFT JOIN is such a join which specifies that all records be fetched from the table on the left
side of the join statement. If a record returned from the left table has no matching record in the table
on the right side of the join, it is still returned, and the corresponding column from the right table
returns a NULL value.

SELECT * FROM table_A


LEFT JOIN table_B
ON table_A.A=table_B.A;

MySQL RIGHT JOIN

The RIGHT JOIN is such a join which specifies that all records be fetched from the table on the
right side of the join statement, even if the table on the left has no matching record. In this case, the
columns from the left table return NULL values.

SELECT * FROM table_A


RIGHT JOIN table_B
ON table_A.A=table_B.A;

MySQL CROSS JOIN

A CROSS JOIN is such a join which specifies the complete cross product of two tables. For each
record in the first table, all the records in the second table are joined, creating a potentially huge
result set. This command has the same effect as leaving off the join condition, and its result set is
also known as a Cartesian product.

Example
view plaincopy to clipboardprint?

SELECT * FROM table_A


CROSS JOIN table_B;

inner join oupput

MySQL NATURAL JOIN

A NATURAL JOIN is such a join that performs the same task as an INNER or LEFT JOIN, in
which the ON or USING clause refers to all columns that the tables to be joined have in common.

Example
view plaincopy to clipboardprint?

SELECT * FROM table_A


NATURAL JOIN table_B;

DELETE STATEMENT:

It is used to delete rows from a table. If you want to remove a specific row from a table you should
use WHERE condition.

SQL>DELETE FROM table_name [WHERE condition];

But if you do not specify the WHERE condition it will remove all the rows from the table.
SQL>DELETE FROM table_name;

There are some more terms similar to DELETE statement like as DROP statement and TRUNCATE
statement but they are not exactly same there are some differences between them.

Difference between DELETE and TRUNCATE statements

There is a slight difference b/w delete and truncate statement. The DELETE statement only deletes
the rows from the table based on the condition defined by WHERE clause or delete all the rows
from the table when condition is not specified.

But it does not free the space containing by the table.

The TRUNCATE statement: it is used to delete all the rows from the table and free the
containing space.

SQL> TRUNCATE TABLE employee;

Difference b/w DROP and TRUNCATE statements

When you use the drop statement it deletes the table's row together with the table's definition so all
the relationships of that table with other tables will no longer be valid.

When you drop a table:

Table structure will be dropped

Relationship will be dropped


Integrity constraints will be dropped
Access privileges will also be dropped

On the other hand when we TRUNCATE a table, the table structure remains the same, so you will
not face any of the above problems.

TO RENAME TABLE
It is used to change the name of a table. Sometimes, we choose non-meaningful name for the table.
So it is required to be changed.

SQL>ALTER TABLE table_name


RENAME TO new_table_name;

or

SQL> RENAME old_table _name To new_table_name;

SQL> RENAME STUDENTS TO ARTISTS;

After that the table "students" will be changed into table name "artists"
It is used to change the name of a table. Sometimes, we choose non-meaningful name for the table.
So it is required to be changed.

Natural Join

In MySQL, the NATURAL JOIN is such a join that performs the same task as an INNER or LEFT
JOIN, in which the ON or USING clause refers to all columns that the tables to be joined have in
common.

The MySQL NATURAL JOIN is structured in such a way that, columns with the same name of
associate tables will appear once only.

Natural Join : Guidelines :

The associated tables have one or more pairs of identically named columns.
The columns must be the same data type.
Don’t use ON clause in a NATURAL JOIN.

Mysql> select * from table 1 natural join table 2;

Setting of default value:

ALTER TABLE emp


ALTER COLUMN City SET DEFAULT 'noida';

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE emp


ALTER City DROP DEFAULT;

Eliminating Duplicate rows:

Select distinct col1,col2 from table1;


Select distinct * from table name;

You might also like