0% found this document useful (0 votes)
21 views11 pages

SQL Notes

present sql
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
21 views11 pages

SQL Notes

present sql
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

These commands allow users to perform various actions on a database.

This article will teach us about SQL commands or SQL


sublanguage commands like DDL, DQL, DML, DCL, and TCL.
DDL (Data Definition Language)
DDL or Data Definition Language used to define the database schema. It simply deals with descriptions of the database schema and is used to
create and modify the structure of database objects in the database. A set of SQL commands used to create, modify, and delete database
structures but not data. These commands are normally not used by a general user, who should be accessing the database via an application.
List of DDL Commands

Command Description Syntax

Create database or its objects (table, index, CREATE TABLE table_name (column1
CREATE
function, views, store procedure, and triggers) data_type, column2 data_type, ...);

DROP Delete objects from the database DROP TABLE table_name;

ALTER TABLE table_name ADD COLUMN


ALTER Alter the structure of the database
column_name data_type;

Remove all records from a table, including all


TRUNCATE TRUNCATE TABLE table_name;
spaces allocated for the records are removed

COMMENT 'comment_text' ON TABLE


COMMENT Add comments to the data dictionary
table_name;

RENAME TABLE old_table_name TO


RENAME Rename an object existing in the database
new_table_name;

DQL (Data Query Language)


DQL statements are used for performing queries on the data within schema objects. The purpose of the DQL Command is to get some schema
relation based on the query passed to it. We can define DQL as follows it is a component of SQL statement that allows getting data from the
database and imposing order upon it. It includes the SELECT statement.

Command Description Syntax

SELECT It is used to retrieve data from the database SELECT column1, column2, ...FROM table_name<br>WHERE condition;

DML(Data Manipulation Language)


The SQL commands that deal with the manipulation of data present in the database belong to DML or Data Manipulation Language and this
includes most of the SQL statements. It is the component of the SQL statement that controls access to data and to the database.
List of DML commands

Command Description Syntax

INSERT INTO table_name (column1, column2, ...) VALUES (value1,


INSERT Insert data into a table
value2, ...);

Update existing data within a UPDATE table_name SET column1 = value1, column2 = value2 WHERE
UPDATE
table condition;

Delete records from a database


DELETE DELETE FROM table_name WHERE condition;
table

LOCK Table control concurrency LOCK TABLE table_name IN lock_mode;


Command Description Syntax

CALL Call a PL/SQL or JAVA subprogram CALL procedure_name(arguments);

EXPLAIN
Describe the access path to data EXPLAIN PLAN FOR SELECT * FROM table_name;
PLAN

DCL (Data Control Language)


DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of the database
system.
List of DCL commands:

Command Description Syntax

Assigns new privileges to a user account, GRANT privilege_type [(column_list)] ON


GRANT allowing access to specific database objects, [object_type] object_name TO user [WITH
actions, or functions. GRANT OPTION];

Removes previously granted privileges from a REVOKE [GRANT OPTION FOR] privilege_type
REVOKE user account, taking away their access to [(column_list)] ON [object_type] object_name
certain database objects or actions. FROM user [CASCADE];

TCL (Transaction Control Language)


Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the
group are successfully completed. If any of the tasks fail, the transaction fails.
Therefore, a transaction has only two results: success or failure.

Command Description Syntax

BEGIN TRANSACTION Starts a new transaction BEGIN TRANSACTION [transaction_name];

COMMIT Saves all changes made during the transaction COMMIT;

ROLLBACK Undoes all changes made during the transaction ROLLBACK;

SAVEPOINT Creates a savepoint within the current transaction SAVEPOINT savepoint_name;

Important SQL Commands


Some of the most important SQL commands are:
1. SELECT: Used to retrieve data from a database.
2. INSERT: Used to add new data to a database.
3. UPDATE: Used to modify existing data in a database.
4. DELETE: Used to remove data from a database.
5. CREATE TABLE: Used to create a new table in a database.
6. ALTER TABLE: Used to modify the structure of an existing table.
7. DROP TABLE: Used to delete an entire table from a database.
8. WHERE: Used to filter rows based on a specified condition.
9. ORDER BY: Used to sort the result set in ascending or descending order.
10. JOIN: Used to combine rows from two or more tables based on a related column between them.
SQL Commands With Examples
The examples demonstrates how to use an SQL command. Here is the list of popular SQL commands with Examples.

SQL
Command Example

SELECT SELECT * FROM employees;


SQL
Command Example

INSERT INSERT INTO employees (first_name, last_name, email) VALUES ('John', 'Doe', 'john.doe@example.com');

UPDATE UPDATE employees SET email = 'jane.doe@example.com' WHERE first_name = 'Jane' AND last_name = 'Doe';

DELETE DELETE FROM employees WHERE employee_id = 123;

CREATE
CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50));
TABLE

ALTER TABLE ALTER TABLE employees ADD COLUMN phone VARCHAR(20);

DROP TABLE DROP TABLE employees;

WHERE SELECT * FROM employees WHERE department = 'Sales';

ORDER BY SELECT * FROM employees ORDER BY hire_date DESC;

SELECT e.first_name, e.last_name, d.department_name FROM employees e JOIN departments d ON e.department_id


JOIN = d.department_id;

A.C.I.D. properties: Atomicity, Consistency, Isolation, and Durability

ACID is an acronym that refers to the set of 4 key properties that define a transaction: Atomicity, Consistency, Isolation, and
Durability. If a database operation has these ACID properties, it can be called an ACID transaction, and data storage systems
that apply these operations are called transactional systems. ACID transactions guarantee that each read, write, or
modification of a table has the following properties:

Atomicity - each statement in a transaction (to read, write, update or delete data) is treated as a single unit. Either the entire
statement is executed, or none of it is executed. This property prevents data loss and corruption from occurring if, for example,
if your streaming data source fails mid-stream.

Consistency - ensures that transactions only make changes to tables in predefined, predictable ways. Transactional consistency
ensures that corruption or errors in your data do not create unintended consequences for the integrity of your table.

Isolation - when multiple users are reading and writing from the same table all at once, isolation of their transactions ensures
that the concurrent transactions don't interfere with or affect one another. Each request can occur as though they were
occurring one by one, even though they're actually occurring simultaneously.

Durability - ensures that changes to your data made by successfully executed transactions will be saved, even in the event of
system failure

Introduction

MySQL is one of the most popular open-source Relational Database Management Systems (RDBMS).A MySQL client might hold
multiple databases. Each database might contain multiple tables with each table holding data of the same type. Each table contains
rows and columns with each row denoting a single entry and each column denoting different attributes of the entries. Data Types in
MySQL

MySQL supports a list of predefined data types that we can use to effectively model our tables. These data types are:
• INT: for integer data.
• DECIMAL: for decimal data.
• BOOLEAN: for boolean data.
• CHAR: for fixed-length string.
• VARCHAR: for variable-length string.
• TEXT: for long-form text.
• DATE: for date data.
• TIME: for time data.
• DATETIME: for date-time data.
• TIMESTAMP: for timestamp data.
MySQL Commands

CREATE TABLE

The CREATE TABLE statement is used in MySQL to create a new table in a database. The syntax for this is shown below:

CREATE TABLE [IF NOT EXISTS] table_name(


column1_definition, column2_definition,
..., table_constraints

);

DROP TABLE

The DROP TABLE statement is used in MySQL to drop or delete a table from the database. The syntax for this is shown below:

DROP [TEMPORARY] TABLE [IF EXISTS] table_name;

RENAME TABLE

The RENAME TABLE statement is used in MySQL to rename the existing tables. One or more tables can be renamed using this
statement:

RENAME TABLE old_table_name to new_table_name;

INSERT INTO

The INSERT INTO statement is used in MySQL to insert rows into a table. One or more rows can be inserted into a table using this
statement.

INSERT INTO table_name (column1, column2, ….)

VALUES (value1, value2, ....),

(value1, value2, ...),


(value1, value2, ...),

....................;
SELECT

The SELECT statement is used for querying data. It allows you to select data from one or more tables.

Syntax:

SELECT column1, column 2,....


FROM table_name;
SELECT DISTINCT

The SELECT DISTINCT statement is used in MySQL to remove duplicate rows.

SELECT DISTINCT column1, column2,...


FROM table_name;
ALTER TABLE

The statement ALTER TABLE can be used in MySQL to add a column, modify a column, drop a column, rename a column from a
table.

1. Add a column to a table using ALTER TABLE with ADD The syntax
for adding a column to a table is shown below:

ALTER TABLE table_name


ADD
new_column_name column_definition
[FIRST|AFTER column_name]
2. Modify a column using ALTER TABLE with MODIFY

We can modify one or multiple columns of a table using MODIFY with ALTER TABLE statement.

ALTER TABLE table_name


MODIFY
column_name column_definition
[FIRST|AFTER column_name]
3. Rename columns using ALTER TABLE with CHANGE COLUMN

We can rename a column of a table using the CHANGE COLUMN keyword with ALTER TABLE.

The syntax for this is shown below:

ALTER TABLE table_name


CHANGE COLUMN original_column_name new_column_name column_definition

[FIRST | AFTER column_name]


4. Drop a column using ALTER TABLE with DROP COLUMN

We can drop a column or multiple columns using DROP COLUMN with ALTER TABLE.
The syntax for this is shown below:

ALTER TABLE table_name


DROP COLUMN column_name;
ORDER BY in MySQL

The ORDER BY clause is used in MySQL to sort the retrieved data in a particular order.

Syntax:

SELECT column1, column2,...


FROM table_name

ORDER BY Column1 ASC/DESC, Column2 ASC/DESC,... ;


Aliases in MySQL

Aliases are used to give columns or tables a temporary or simple name. AS keyword is used to create an alias.

Column Alias

The syntax for column name aliases is written below.

Syntax:

SELECT column_name AS given_name


FROM table_name;
Table Alias

The aliases can be used to give simple and different names to tables also.
Syntax:

SELECT column1, column2, ….


FROM table_name AS given_name;
WHERE clause in MySQL

The WHERE clause is used to apply a particular condition while selecting rows from the table. It helps in filtering the rows according
to any particular condition.

Syntax:

SELECT column1, column2, …..


FROM table_name
WHERE condition;
IN Operator in MySQL

The IN operator is used to check if a value matches any of the values in a list of values. It is similar to the OR operator as if any of the
values in the list matches it returns true.

Syntax:

SELECT column1, column2, …..


FROM table_name

WHERE column_name IN (value1, value2, ….);


or

SELECT column1, column2, …..


FROM table_name

WHERE column_name IN (SELECT statement );


LIKE Operator in MySQL

The LIKE operator is used in MySQL to search for a specific pattern in a string. If an expression matches the pattern, it returns true
else false.

There are two wildcards in MySQL, used with the LIKE operator for searching a pattern.

• The percentage sign (%). It represents zero or more characters.


• The underscore sign (_). It represents a single character.

Syntax:

SELECT column1, column2, …..


FROM table_name
WHERE column_name LIKE pattern;

For example:

SELECT customer_id, customer_name, product_id


FROM customers

WHERE customer_name LIKE 'A'%;


IS NULL Operator in MySQL

The IS NULL is used to check if a value is NULL or not. If the value is NULL, it returns true else false.

Syntax:

SELECT column1, column2, …..


FROM table_name

WHERE column_name IS NULL;


JOIN

Joins are used in relational databases to combine data from multiple tables based on a common column between them. A foreign
key may be used to reference a row in another table and join can be done based on those columns. Two or more tables may have
some related data, and to combine all the data from multiple tables joins are used.

There are different types of joins in MySQL.

1. INNER JOIN 2. LEFT JOIN


3. RIGHT JOIN
4. CROSS JOIN

INNER JOIN

The INNER JOIN produces the output by combining those rows which have matching column values.

Syntax:

SELECT column_names
FROM table1
INNER JOIN table2 ON table1.common_column=table2.common_column INNER
JOIN table3 ON table1.common_column=table3.common_column

...;
LEFT JOIN

The LEFT JOIN returns all the rows from the left table ‘A’ and the matching rows from the right table ‘B’ in the join. The rows from
the left table, which have no matching values in the right table will be returned with a NULL value in the link column.
Syntax:

SELECT column_names
FROM table1

LEFT JOIN table2 ON table1.common_column=table2.common_column;


RIGHT JOIN

The RIGHT JOIN returns all the rows from the right table ‘B’ and the matching rows from the left table ‘A’ in the join. The rows from
the right table, which have no matching values in the left table will be returned with a NULL value in the link column.

Syntax:

SELECT Column_names
FROM table1
RIGHT JOIN table2 ON table1.common_column=table2.common_column;
CROSS JOIN

CROSS JOIN returns the cartesian product of rows from the tables in the join. It combines each row of the first table with each row
of the second table. If there are X rows in the first table and Y rows in the second table then the number of rows in the joined table
will be X*Y.

Syntax:
SELECT column_names
FROM table1
CROSS JOIN table2;
GROUP BY

The GROUP BY clause is used to arrange the rows in a group using a particular column value. If there are multiple rows with the
same value for a column then all those rows will be grouped with that column value.

Syntax:

SELECT column1,column2,…
FROM table_name
WHERE condition
GROUP BY column1,column2, …

Order BY column1, column2, ….


The GROUP BY clause is generally used with aggregate functions like SUM, AVG, COUNT, MAX, MIN. The aggregate functions provide
information about each group.

HAVING

The HAVING clause is used with the GROUP BY clause in a query to specify come conditions and filter some groups or aggregates
that fulfill those conditions. The difference between WHERE and HAVING is, WHERE is used to filter rows, and HAVING is used to
filter groups by applying some conditions.

Syntax:

SELECT column1, column2, …


FROM table_name
WHERE conditions
GROUP BY column1, column2, …..

HAVING conditions

An index helps to speed up select queries and where clauses, but it slows down data input, with the update and the insert
statements.

Creating an Index
Syntax
CREATE INDEX index

ON TABLE column;

where the index is the name given to that index TABLE is the name of the table on which that index is created and column is the
name of that column for which it is applied.

For Multiple Columns


Syntax:

CREATE INDEX index

ON TABLE (column1, column2,…..);


For Unique Indexes
Unique indexes are used for the maintenance of the integrity of the data present in the table as well as for fast performance, it does
not allow multiple values to enter into the table.

Syntax:

CREATE UNIQUE INDEX index

ON TABLE column;

When Should Indexes be Created?


A column contains a wide range of values.
A column does not contain a large number of null values.
One or more columns are frequently used together in a where clause or a join condition.
When Should Indexes be Avoided?
The table is small
The columns are not often used as a condition in the query
The column is updated frequently
Removing an Index
Remove an index from the data dictionary by using the DROP INDEX command.

Syntax
DROP INDEX index;

To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.

Altering an Index
To modify an existing table’s index by rebuilding, or reorganizing the index.

ALTER INDEX IndexName

ON TableName REBUILD;

Confirming Indexes
You can check the different indexes present in a particular table given by the user or the server itself and their uniqueness.

Syntax:

SELECT * from USER_INDEXES;

It will show you all the indexes present in the server, in which you can locate your own tables too.

Renaming an Index
You can use the system-stored procedure sp_rename to rename any index in the database.

Syntax:

EXEC sp_rename
index_name,
new_index_name,
N’INDEX’;

SQL Server Database


Syntax: DROP INDEX TableName.IndexName;
Difference between SQL and MySQL
SN Parameter MySQL SQL

1. Definition MySQL is the popular open-source database available in SQL (Structured Query Language) is a
the market, which is developed by the Swedish programming language that is useful for managing
company MySQL AB. our relational databases.

2. Purpose MySQL used for data handling, storing, deleting, and It is used to query and operate the database.
updating the data in tabular form.

3. Updates MySQL is software, so it gets frequent updation. The SQL is a programming language; that's why it does
current stable version is v8.0.20, which provides two not get any updates. Its commands or statements
times faster speed than the previous versions. always fixed and remain the same.

4. Type It is database software that uses SQL language to It is a query language for managing databases.
conduct with the database.

5. Complexity It is easily used through simple downloading and It requires learning the language to use it
installation. effectively.

6. Usage MySQL is used as RDBMS for managing relational SQL commands or statements are used in various
databases. DBMS and RDBMS. MySQL itself uses SQL
commands.

7. Support for It provides the MySQL Workbench tool to design and No connectors are available in SQL.
Connectors develop databases.

8. Multilingual It is available only in the English language. It is available in many different languages.

9. Flexibility It does not provide support for XMAL and user-defined It includes support for XMAL and user-defined
functions. functions.

10. Community MySQL is free to use so that it has very rich community It does not have excellent community support. If
Support support. we find any problem, we need to go to Microsoft
SQL Server support.

11. Advantage Open-Source. No need for coding.


Data security. High speed.
High Performance. Portability.
Data Security. Multiple views of data.
Complete workflow controls. Interactive language.

You might also like