0% found this document useful (0 votes)
29 views14 pages

Important MYSQL Commands

The document defines key database concepts like relations, domains, tuples, attributes, primary keys, foreign keys and constraints. It also explains SQL commands, data types, aggregate functions and differences between SQL clauses and commands like SELECT, DELETE, ALTER and UPDATE.

Uploaded by

deetyarupani
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)
29 views14 pages

Important MYSQL Commands

The document defines key database concepts like relations, domains, tuples, attributes, primary keys, foreign keys and constraints. It also explains SQL commands, data types, aggregate functions and differences between SQL clauses and commands like SELECT, DELETE, ALTER and UPDATE.

Uploaded by

deetyarupani
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/ 14

Key Terms

Relation:- In database, a relation means a 'table', in which data is organized in the form of
rows and columns. Therefore in database, relations are equivalent to tables.
Domain: A domain is the original sets of atomic values used to model data. It refers to all the
possible unique values of a particular column.
For example:
i) The domain of gender column has a set of two possible values i.e, Male or Female.
ii) The domain of marital status has a set of four possible values i.e, Married, Unmarried,
Widows and Divorced.
Tuple: -The horizontal subset of a Table is known as a Row or Tuple.
Attribute:- The vertical subset of a Table is known as a Column or Attribute.
Degree: - The degree is the number of attributes (columns) in a table.
Cardinality: -Cardinality is number of rows (tuples) in a table.
Primary Key: A column or set of columns that uniquely identifies a row within a table is called
primary key.
Candidate Key: Candidate keys are set of fields (columns with unique values) in the relation
that are eligible to act as a primary key.
Alternate Key: Out of the candidate keys, after selecting a key as primary key, the remaining
keys are called alternate key.
Foreign Key: A foreign key is a field (or collection of fields) in one table that uniquely identifies
a row of another table. In other words, a foreign key is a column or a combination of columns
that is used to establish a link between two tables.
SQL Commands:
SQL commands are instructions, coded into SQL statements, which are used to communicate
with the database to perform specific tasks with data.
SQL commands are grouped into four major categories depending on their functionality:
Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and
dropping the structure of database objects. The commands are CREATE, ALTER, DROP,
RENAME, and TRUNCATE.
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data.
These Data Manipulation Language commands are: SELECT, INSERT, UPDATE, and DELETE.
Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
Data Control Language (DCL) - These SQL commands are used for providing security to
database objects. These commands are GRANT and REVOKE.

Data Type

Each value manipulated by SQL Database has a data type. The data type of a value associates a
fixed set of properties with the value. In SQL there are three main data types: Character,
Number, and Date types.

Difference between Alter and Update Command


Alter Command Update Command
Alter command is Data Definition Language Update command is Data Manipulation
Command. Language Command.
Alter command is used to add, modify and Update command is used to make changes in
delete a column from the table. the record of the table.
Difference between Where Clause and Having Clause
Where Clause Having Clause
It is used to filter the records from the table It is used to filter out records from the groups
based on a specific condition. based on a specific condition.
It can be used without the ‘GROUP BY’ clause. It can’t be used without the ‘GROUP BY’
clause.
It can be used with row operations. I t works with the column operation.
It can’t contain the aggregate functions. It can contain the aggregate functions.
It can be used with the ‘SELECT’, ‘UPDATE’, It can only be used with the ‘SELECT’
and ‘DELETE’ statements. statement.
It is used before the ‘GROUP BY’ clause if It is used after the ‘GROUP BY’ clause.
required.
It is used with a single row function such as It can be used with multiple row functions
‘UPPER’, ‘LOWER’. such as ‘SUM’, ‘COUNT’.

Difference between Group By Clause and Order by Clause


Group By Clause Order by Clause
The Group by clause is used to display the The Order by Clause is used to display the
records that have identical value in a records either in ascending or descending
particular field or a group of fields. order base on a particular field. For ascending
order ASC is used and for descending order,
DESC is used. The default order is ascending
order
GROUP BY is always placed before the ORDER ORDER BY is always placed after the GROUP
BY clause in the SELECT statement. BY clause in the SELECT statement.
It is mandatory to use the aggregate function It’s not mandatory to use the aggregate
to use the Group By function to use the Order By.
Difference between DELETE Command, DROP Command and TRUNCATE Command

DELETE Command DROP Command TRUNCATE Command


The DELETE command is Data The DROP command is Data The TRUNCATE command is a
Manipulation Language Definition Language Data Definition Language
Command. Command. Command.
The TRUNCATE Command
The DELETE command deletes The DROP Command drops
deletes all the rows from the
one or more existing records the complete table from the
existing table, leaving the row
from the table in the database. database.
with the column names.
We can restore any deleted We cannot get the complete
We cannot restore all the
row or multiple rows from the table deleted from the
deleted rows from the database
database using the ROLLBACK database using the
using the ROLLBACK command.
command. ROLLBACK command.
DELETE FROM table_name
DROP TABLE table_name; TRUNCATE TABLE table_name;
WHERE condition;
Constraints
While designing Relational Model, we define some conditions which must hold for data
present in database are called Constraints. These constraints are checked before performing
any operation (insertion, deletion and updation) in database. If there is a violation in any of
constrains, operation will fail.

NOT NULL Constraint


By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.

UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

FOREIGN KEY Constraint


The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.

CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

DEFAULT Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.

Referential integrity refers to the accuracy and consistency of data within a relationship.

In relationships, data is linked between two or more tables. This is achieved by having the
foreign key (in the associated table) reference a primary key value (in the primary – or parent
– table). Because of this, we need to ensure that data on both sides of the relationship remain
intact.
Referential Integrity: When one attribute of a relation can only take values from other
attribute of same relation or any other relation, it is called referential integrity.
Referential integrity is a subset of data integrity,

Aggregate Functions

A single row function works on a single value. SQL also provides us multiple row functions. A
multiple row function works on multiple values. These functions are called aggregate
functions or group functions. These functions are:
1 MAX() Returns the MAXIMUM of the values under the specified column/expression.
2 MIN() Returns the MINIMUM of the values under the specified column/expression.
3 AVG() Returns the AVERAGE of the values under the specified column/expression.
4 SUM() Returns the SUM of the values under the specified column/expression.
5 COUNT() Returns the COUNT of the number of values under the specified
column/expression.

Important MYSQL Commands


1. To see a list of all databases available
Show databases
2. To create a new database
Create database database_name;
3. To use any database
Use database_name
4. To delete a database
Drop database database_name
5. To know the database currently in use
select database()
6. To create a table
CREATE TABLE TableName (ColumnName1 DataType1 (size), ColumnName2 DataType2
(size),…………………………. , ColumnNameN Data TypeN (size));
7. To Rename a table name:
ALTER TABLE table_name rename to new_table_name;
8. To View the Structure of a Table
DESCRIBE table_name;
OR
DESC table_name;
9. To delete the table with its structure
Drop table table_name
10. To see all table available in the database selected
Show tables
11. To Rename a column in a table:
ALTER TABLE tablename CHANGE oldname newname datatype (size) ;
12. To add a new column
ALTER TABLE tablename ADD ColumnName datatype (size);
13. To delete the column
ALTER TABLE tablename drop ColumnName
14. To modify the column data type or size
ALTER TABLE tablename modify ColumnName new_datatype (new_size);
15. To create a table with constraints primary key, not null , default ,check

CREATE TABLE TableName (ColumnName DataType (size) primary key, ColumnName


DataType (size) not null, ColumnName DataType (size) default(value), ColumnName

DataType (size) check(condition) );

16. To create a table with foreign key constraint

Create table TableName (ColumnName DataType (size), ColumnName DataType (size),


foreign key (ColumnName) references parent_table_name (ColumnName));

17. To add a primary key in a already created table

ALTER TABLE tablename ADD PRIMARY KEY (ColumnName);


18. To add a primary key in a already created table with a combination of two columns
ALTER TABLE TableName ADD PRIMARY KEY (ColumnName1, ColumnName2);
19. To delete the primary key
ALTER TABLE TableName DROP PRIMARY KEY
20. To create a table from a existing table with its all data
Create table tablename as (select columnName from existing_tablename)
21. To create a table from a existing table without its data
Create table tablename as (select columnName from existing_tablename where false
condition)
Retrieving Information with SELECT Statement

22. To count the number of columns in a table


Select count (ColumnName) from TableName
or
Select count (*) from TableName
23. To eliminate the duplicate values from a table
Select distinct (ColumnName) from TableName
24. To show the records within a range of values
Select * from TableName where column between value1 and value2
25. To show specific values from a table
Select * from TableName where column in (value1, value2,….., value N)
26.To show the records that follows any pattern use like operator
% and _ are two wild card characters. The percent (%) symbol is used to represent any
sequence of zero or more characters. The underscore (_) symbol is used to represent a single
character.
Select * from TableName where column like ‘condition’
27. To show the records in ascending or descending order
Select * from TableName order by ColumnName asc / desc
28. ‘=’ is not used in ‘where’ clause when we are working on NULL values. At the place of ‘=’
we use ‘is’.

Select * from TableName where ColumnName is null


Or
Select * from TableName where ColumnName is not null
29. Using Comparison operators : =,<,>, <=, >=, !=
Select * from TableName where ColumnName > value
30. Using relational operator and , or
Select * from TableName where ColumnName1 condition1 and ColumnName2
condition2
31. To update the records
Update TableName set ColumnName=new_value condition
32. GROUP BY: GROUP BY clause is used in a SELECT statement in conjunction with aggregate
functions to group the result based on distinct values in a column.
HAVING: HAVING clause is used in conjunction with GROUP BY clause in a SELECT statement to
put condition on groups.
Select ColumnName from TableName group by ColumnName
If you want to put a condition on group by clause , use having instead of where
Select ColumnName from TableName group by ColumnName having condition
JOIN
When we combine rows of two or more tables based on a common column between them,
this operation is called joining

CARTISIAN PRODUCT: The Cartesian product of two relations is the concatenation of tuples
belonging to the two relations.
The degree of the new relation is the sum of the degrees of two relations on which Cartesian
product is operated. The Cardinality of the new relation is equal to the product of number of
tuples of the two relations on which Cartesian product is operated.

The Cartesian product is also referred to as a cross-join, returns all the rows in all the tables
listed in the query.

Types of Joins:
 Equi- join
 Natural Join
 Non-equi join
Equi – Join: An equi-join is an operation that combines multiple tables based on equality or
matching column values in the associated tables. It is also called as inner join or simple join.
Points to remember:
 There is no need to be the same column names.
 The resultant result can have repeated column names.
 We can also perform an equijoin operation on more than two tables.
Syntax:

The following are the basic syntax that illustrates the equijoin operations:
SELECT column_name(s) FROM table_name1, table_name2 WHERE
table_name1.column_name = table_name2.column_name;
OR
SELECT (column_list | *) FROM table_name1 INNER JOIN table_name2 ON
table_name1.column_name = table_name2.column_name;

Natural Join: A natural join is a type of join operation that creates an implicit join by
combining tables based on columns with the same name and data type. It is similar to the
INNER or LEFT JOIN, but we cannot use the ON or USING clause with natural join as we used in
them.

Points to remember:
 There is no need to specify the column names to join.
 The resultant table always contains unique columns.
 It is possible to perform a natural join on more than two tables.
 Do not use the ON clause.

Syntax:
The following is a basic syntax to illustrate the natural join:

SELECT [column_names | *] FROM table_name1 NATURAL JOIN table_name2;

Equi Join and Natural Join Example:

First, we will create two tables named customer and balance using the below statements:

CREATE TABLE customer ( id INT AUTO_INCREMENT PRIMARY KEY, customer_name


VARCHAR(55), account int, email VARCHAR(55) );

CREATE TABLE balance ( id INT AUTO_INCREMENT PRIMARY KEY, account int,balance


FLOAT(10, 2) );

Next, we will fill some records into both tables using the below statements:

INSERT INTO customer(customer_name, account, email)


VALUES('Stephen', 1030, 'stephen@gmail.com'),
('Jenifer', 2035, 'jenifer@ gmail.com'),
('Mathew', 5564, 'mathew@ gmail.com'),
('Smith', 4534, 'smith@ gmail.com'),
('David', 7648, 'david@ gmail.com');

INSERT INTO balance(account, balance)


VALUES(1030, 50000.00), (2035, 230000.00), (5564, 125000.00),
(4534, 80000.00), (7648, 45000.00);

Execute the below statement for joining tables using natural join:

mysql> SELECT customer_name, balance FROM customer NATURAL JOIN balance;

We can do the same job with the help of INNER JOIN using the ON clause. Here is the query
to explain this join:

SELECT customer_name, balance FROM customer INNER JOIN balance ON customer.id =


balance.id;

Now, we will use (*) in the place of column names as follows:


mysql> SELECT * FROM customer NATURAL JOIN balance;

Suppose we use the asterisk (*) in the place of column names, then the natural join
automatically searches the same column names and their data types and join them internally.
Also, it does not display the repeated columns in the output. Hence, we should get the below
output after executing the above statement:

mysql> SELECT * FROM customer INNER JOIN balance ON customer.id = balance.id;

Natural Join with WHERE Clause

The WHERE clause is used to return the filter result from the table. The following example
illustrates this with the natural join clause:

mysql> SELECT cust. customer_name, bal.balance FROM customer AS cust NATURAL


JOIN balance AS bal WHERE bal.balance > 50000;

Non Equi-join: When there is no common column in two table and we perform a join then this
type of join is called non-equi join.
Example: Teacher table attributes: TN0 , TNAME, TADDRESS, SALARY, DEPT_NO,DOJ
Grade table attributes: GRADE, MINSAL, MAXSAL
In these tables there is no common column. So, it is not possible to perform equi-join. The
only relationship between the two tables is that the salary in the teacher table is in between
minsal and maxsal column of the grade table. So, we cannot obtain the result using the ‘=’
operator.
Thus the query will be:
SELECT T.TNAME, T.SALARY, G.GRADE FROM TEACHER T , GRADE G WHERE T.SALARY
BETWEEN G.MINSAL AND G.MAXSAL;
Sub-Queries: When you place one query inside another query then it is called a sub query. In
the sub query, the inner query generates values that are tested in the conditions of the outer
query.

Example: Write a query to display the teacher names whose salary is greater than the salary
of teacher number T05.
SELECT TNAME FROM TEACHER WHERE SALARY > (SELECT SALARY FROM TEACHER WHERE TNO=’T05’)
UNION OPERATION
Union is an operation of combining the output of two select statements. Union of two select
statements can be performed only if their outputs contain same number of columns and same
data types of the corresponding columns.
Syntax:
Select columns from table where condition union Select columns from table where
condition.
To use union , each select statement must have the same number of columns selected and
same data types of the corresponding columns and must have them in the same order, but
they do not need to be of the same length.
The UNION operator selects only distinct values by default. To allow duplicate values, use the
ALL keyword with UNION.
For example: There are two tables called ‘Class12A’ and ‘Class12B’ with same columns like:
Field Name Field Type
RegNo Varchar(10)
Name Varchar(50)
City Varchar(50)
Two tables contain the following data:
Class12A
RegNo Name City
NIS101 Amit Kumar Kanpur
NIS102 Akash Goel Lucknow
NIS103 Om Verma Agra
NIS104 Vishwash Kumar Chennai
NIS105 Ramesh Pal New Delhi
NIS106 Prakhar Kumar Lucknow
NIS110 Nitin Patel Chennai

Class12B
RegNo Name City
NIS106 Prakhar Kumar Lucknow
NIS107 Ratandeep Kanpur
NIS108 K.K Malhotra Agra
NIS109 Maria New Delhi
NIS110 Nitin Patel Chennai
NIS102 Akash Goel Lucknow
NIS105 Ramesh Pal New Delhi
Write a query to display all the rows from the ‘Class12A’ and the ‘Class12B’ tables in ascending
order of city.
Select * from class12A UNION select * from class 12B order by city;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy