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

SQL Basics and MySQL Queries Overview

The document discusses MySQL, a relational database management system. It covers basic concepts like what is a database and database management system. It then explains key aspects of MySQL like the different types of databases it supports, SQL queries for creating and interacting with databases and tables, different data types, keys and constraints. The document also provides examples of various SQL queries for performing CRUD operations, joining tables, altering schemas and truncating data.

Uploaded by

kamlesh asolkar
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)
21 views26 pages

SQL Basics and MySQL Queries Overview

The document discusses MySQL, a relational database management system. It covers basic concepts like what is a database and database management system. It then explains key aspects of MySQL like the different types of databases it supports, SQL queries for creating and interacting with databases and tables, different data types, keys and constraints. The document also provides examples of various SQL queries for performing CRUD operations, joining tables, altering schemas and truncating data.

Uploaded by

kamlesh asolkar
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

MySQL

Link for the video - [Link]

What is Database?
DB is collection of data in a format that can be easily accessed (digital).
A Software application used to manage our DB is called DBMS (database management
system).

We don’t directly access the db it is accessed by a software application called as DBMS.


We use SQL for the DBMS to interact.

Type of DataBase –
1. Relational (RDMS) – Data stored in table and we use sql to interact. Some ex. Of
relational db are – MySQL, ORACLE, Microsoft SQL SERVER, and PostgreSQL.

2. Non-Relational (NoSQL) - Data not stored in table form. Ex mongo DB.

What is SQL?
SQL (Structured Query Language) is programming language use to interact with relational
database.
SEQUEL and SQL both are same.
It is use to perform CRUD operation.
 C - Create
 R – Read
 U – Update
 D – Delete

1
Queries (queries are not case sensitive) -

1. Create Database –

Syntax – CREATE DATABASE db_name;

This query is used to create database.


Database called classroom is created.

2. Show Databases-
Syntax – SHOW DATABASES;

This query is used to get/show all the databases present in MySQL.


Here we run this query to see whether the classroom database is created or not.

3. Drop Database –
Syntax – DROP DATABASE db_name;

2
This query is to drop/delete the existing database present in MySQL.
Here from show database query we have checked whether the database we wanted
To drop is dropped or not.

4. Use Database -
Syntax – USE db_name;

This query is used to work in database that we have selected in MySQL.


Here firstly we have created a database named college to interact with it by USE
query.

5. Create Table –
Syntax – CREATE TABLE table_name (
Column_name1 datatype constraint,
Column_name2 datatype constraint,
Column_name3 datatype constraint
);

3
This query is used to create table under the chosen database.
In this syntax we use data types and constraint to create table.
About constraint we will discuss later in detail.

6. Show fields–
Syntax – SHOW fields FROM table_name;
SHOW columns FROM table_name;

This query is used to see all the field, data types, and the constraints.

7. Insert data in table-

Syntax – INSERT INTO table_name VALUES (column1_v1, column2_v2,


column3_v2), (column1_v1, column2_v2, column3_v3);

4
Here we have inserted to 2 column using this query. Remember Column
constraint containing Primary key should be different to avoid ERROR.

8. Show table –
Syntax –SELECT * FROM table_name;

This query is to get all the row and column from the table.
‘*’ means all in SELECT related queries.

Data Types in MySQL -

Difference in CHAR and VARCHAR –


 CHAR is inefficient beacause it reserve the given length whether it is needed or not
but
 VARCHAR is efficient and preffered because it uses the required length.

Signed and Unsigned Data types –


5
Unsigned data types is used for positive integer and to increase the range.
Signed data types is used to both +ve and –ve integer.
For Ex. TINYINT UNSIGNED (0 TO 255)  the –ve number were occupying the range has
been send to +ve int.
TINYINT (-127 TO 128).

Types of SQL Commands –

1. DDL (Data Definition Language): Create, alter, rename, truncate & drop.
2. DQL (Data Query Language) : Select
3. DML (Data Manipulation Language) : , insert, update & delete
4. DCL (Data Control Language): grant & revoke permission to users
5. TCL (Transaction Control Language): start transaction , commit, rollback

Database Related Queries:

1. If Not Exists-
Syntax – CREATE DATABASE IF NOT EXISTS db_name;

2. If Exists-
Syntax – DROP DATABASE IF EXISTS db_name;

This used to avoid error in MySQL but it shows warning as you can see in above image
This is count as good practice in MySQL.

Practice Question at time-lapse (51:54) Solved ----

6
Keys:

1. Primary keys – It is a column or set of column in a table that identifies each row.(a
unique id). There is only 1 Primary key and it should be NOT null.
2. Foreign keys- A foreign key is a column or set of columns in a table that refers to the
primary key in different table. There can be multiple FKs and can have duplicate and
null values. (iska use samj aur sikh nhi paya)

Constraints:

1. NOT NULL: Columns cannot have a null value.

2. UNIQUE: All Values in column are different.

7
3. PRIMARY KEY: makes a column unique and not null used only for one.

4. FOREIGN KEY: prevent actions that would destroy links between tables.
5. DEFAULT: sets the default value of a column.

6. CHECK: allows to limit the values entered in table.

8
As you can see we use check as a constrainst in age and it act as a limit to enter data in table.
When i try to cross the limit it shows the error and didn’t insert the values.

 SELECT COMMAND :

This command is used to select the data from the table.


Note:We Created a table to perform all the task.

 Here ‘ * ‘(asterisk) in Select command means to select all.


Syntax: SELECT * FROM table_name;

9
 DISTINCT is used to select only the unique ones.
Syntax: SELECT DISTINCT col_name FROM table_name;

 WHERE CLAUSE is used to define some conditions.


Syntax: SELECT col1,col2, from table_name
WHERE conditions;

Basic Operator generally used in WHERE CLAUSE :

10
AND & OR Operator : AND is used when both the condition satisfy. OR is used when any
one of the conditions we want to get satisfy.

BETWEEN,IN &NOT: BETWEEN selects for a given [Link] matches any value in the list
If not return nulls .NOT to negate the given condition.

11
 LIMIT CLAUSE:

Use to limit the value to [Link] can use the WHERE condition in it as well.

 ORDER BY CLAUSE:

To sort in ascending(ASC) or Descending(DESC) Order.

 AGGREGATE FUNCTIONS :

To perform a calculation on a set of values, and return a single value.


Some Most Popular Func. Are : COUNT(),MAX(),MIN(),SUM(),AVG().

12
MAX Func. Return max value.

AVG Func. Return avg.

 GROUP By Clause :

It collects data from multiple records and groups that result by one or more
[Link] we use group by with some aggregation func.

 Having Clause:

Similar to WHERE i.e applies some condition on row. Used when we want to apply
any cond. After grouping.

13
 .General Order :

9. UPDATE QUERY (table related) :

To update the existing row in a table.


Syntax: UPDATE table_name
SET col1=val1, col2=val2
WHERE conditions;

[Link] QUERY (table related):

Use to delete the existing row.


Syntax: DELETE FROM table_name
WHERE conditions;

14
As it deleted a row you can see the id 3 is deleted.

Revisiting Foreign key

Basically it link the two different table.

CASCADING IN FOREIGN KEY: Basically means it we update or delete from one table
(parent table) it should reflect in other table (child table) also.

Like you can see we use cascade in FK. Let represent both the tables –

15
Now we delete the deptId which is equal to 1 and that will affect the other table.

Data delete in both the table.

11. ALTER QUERY:

Basically to update the schema and design of the existing table.


Feature of ALTER Query: ADD Column, DROP Column, RENAME Table,
MODIFY Column.

 Add Column :

Syntax: ALTER TABLE table_name


ADD COLUMN column_name dataType constraints;

16
Here we have added an extra Column for the table called stu_detail.

 Drop Column:

Syntax: ATLER TABLE table_name


DROP column_name;

We delete the Column Called city.

 Rename Table :

17
Basically renamed the table.

Syntax: ATLER TABLE table_name


RENAME new_table_name;

Before renaming the table name was stu_detail.

After running the Query –

 Modify Column :

Syntax: ATLER TABLE table_name


MODIFY column_name new_DataType new_Constrainst;

18
[Link] QUERY(table related):

Truncate query basically delete all the data present in the table.
Diff. between Drop and truncate Query is Drop deletes the table but in truncate
the table exist but all the value flushes out.

The values of the table called student deleted. But the table still exists.

19
Joins in SQL

Joins is used to combine rows from two or more tables, based on a related column between
them.

Venn diagram:

 Inner Join: Return records that have matching value in both tables.

Syntax: SELECT column(s)


FROM tableA
INNER JOIN tableB
ON tableA.Col_name=tableB.Col_name;

Firstly We Created a table called student.

Now, we will create a second table called courses have a common column student_id.

20
Now, we will perform Inner Join with this tables.

The result table is combined to two table have common student_id.

Alias is used for alternate name in MySQL. Use in place where we have large table name
To shorten its name. Remember both table names are correct you can use any one of them.

 Left Join: return all records from the left table, and the matches records from the
right table.

Syntax: SELECT column(s)


FROM tableA
LEFT JOIN tableB
ON tableA.Col_name=tableB.Col_name;

21
Just Remember the Sequence of table in this join method because the data of tableA
with appear fully with some common/overlap data of tableB.

We have created the table you have seen in the above join method .So, we will
directly perform the query.
co

The result of tables is shown above you can see the table students represent full data
but in courses the overlapped value appear and in case of absent value printed as
NULL.

 Right Join: returns all records from the right table, and the matched records from the
left table.

Syntax: SELECT column(s)


FROM tableA
RIGHT JOIN tableB
ON tableA.Col_name=tableB.Col_name;

The resulted table is shown above we can see that the course/right side table appear
represent full data and in student table the overlapped data is printed and apart from that
prints NULL.

22
 Full Join: returns all records when there is a match in either left or right table.

Syntax:
SELECT * FROM tableA
LEFT JOIN tableB
LEFT JOIN
ON tableA.Col_name=tableB.Col_name
UNION
UNION
RIGHT JOIN
SELECT * FROM tableA
RIGHT JOIN tableB
ON tableA.Col_name=tableB.Col_name

MySQL don’t have full join so we perform using union. Oracle mei hota hai.

The resulted table Shown above.

Self-Join meko sammj nhi aaya but it exists that is why I mentioned here.

 Union: it is used to combine the result-set of two or more SELECT statements


Given UNIQUE records.

To use it:
 Every SELECT should have same no. of columns.
 Columns must have similar data types.
 Columns in every SELECT should be in same order.

23
Syntax:
SELECT column(s) FROM tableA
UNION
SELECT column(s) FROM tableB;

T
The result print all the data from both the table.

SQL Sub Queries

A Sub query is a query within another SQL query.

SELECT
Query
FROM
WHERE (Sub Query) Sub Query

24
Let’s perform a task to know better about sub query.
Like in a classroom we have to give the name of student who scored more than avg.. . So our
query will be:

SELECT AVG (marks) FROM student;


SELECT name, marks
FROM student
WHERE marks > 87.6667; (this value is the avg. value written here manually)

Suppose a condt. Arrive where we the student score got a mistaken marks given by the
teacher then the overall avg. will be disturb. So, we have to create a dynamic process.
That firstly takeout the avg. of class then perform the selection.

SELECT name, marks


FROM student
WHERE marks > (SELECT AVG (marks) FROM students);

MySQL Views

Views can be basically understand as show up data. For ex. There are multiple data in
database but we show the only data that is required.

25
Syntax: CREATE VIEW view1
SELECT column(s) FROM table_name;

SELECT * FROM view1;

View is the virtual form of table. But table and its data operations are real.

This is not a table Just a view.

THANK YOU

26

Common questions

Powered by AI

Foreign keys in SQL are crucial for maintaining data integrity across tables by establishing and enforcing a link between the data in two tables. A foreign key is a column or set of columns in one table that references the primary key in another table, ensuring that the database maintains the referential integrity of the data. This means that relationships between tables are preserved, preventing actions that would destroy these links, such as deleting or updating a primary key value that is used in a foreign key relationship. Additionally, foreign keys can enforce actions such as cascading updates or deletions, reflecting changes across related tables .

The primary purpose of a Database Management System (DBMS) is to provide a systematic way to create, retrieve, update, and manage data in databases. It facilitates data management by allowing users to interact with the database through SQL (Structured Query Language) for executing CRUD operations (Create, Read, Update, Delete). A DBMS provides a layer of abstraction that prevents direct interaction with the data, offering functionalities such as data security, integrity, concurrency, and recovery while maintaining data independence. Examples of DBMS software include MySQL, Oracle, and Microsoft SQL Server .

Subqueries are preferred over JOINS in scenarios where a hierarchical or nested query is necessary, or when there's a need to perform a calculation or filter data before the outer query can be executed. Subqueries allow for a more readable and modular query structure, particularly when dealing with filtering operations such as obtaining the maximum or minimum value of a particular column, and using that result to filter rows in another query. They can offer performance benefits when the dataset size of the subquery is much smaller than a JOIN operation, which processes entire datasets concurrently. Subqueries also allow for complex logic that might not be easily achievable through JOINS .

The choice between CHAR and VARCHAR data types in MySQL affects storage efficiency and data retrieval. CHAR is fixed-length, meaning it always reserves the specified space, which can lead to inefficiency if the full length is not used. VARCHAR, by contrast, is variable-length, using only the necessary storage space for the data, thus offering better storage efficiency and flexibility. VARCHAR is generally preferred over CHAR for its efficient use of space, particularly in cases where the length of stored data varies significantly .

Views in SQL provide several benefits for data management, including simplifying complex queries by abstracting them into a single object, enhancing data security by limiting user access to specific data, and presenting data in a way that is specific to the needs of individual users or applications without altering the underlying tables. However, views also have limitations, such as potential performance implications due to the recalculation of data each time a view is queried, and complexity when managing updates or edits directly through a view, particularly if the view involves multiple source tables. Additionally, views cannot always be indexed, which can affect retrieval speed .

Aggregate functions in SQL, such as COUNT(), MAX(), MIN(), SUM(), and AVG(), play a critical role in processing queries by performing calculations on a set of values and returning a single value result. These functions enhance data analysis capabilities by allowing users to gain insights from large datasets through summarization and statistical analysis. For example, COUNT() can count the number of records, SUM() can total values, and AVG() can calculate an average. When combined with GROUP BY, aggregate functions enable grouping of result sets based on specific criteria, making it easier to analyze trends and patterns within subsets of data .

Transaction control in SQL greatly influences database reliability and error recovery through mechanisms like COMMIT and ROLLBACK. COMMIT ensures that all changes made during a transaction are permanently saved in the database, promoting consistency and data integrity. ROLLBACK, on the other hand, allows a transaction to be undone, restoring the database to its previous state before the transaction began, which is essential in error recovery scenarios. Combined, these controls help maintain the ACID properties (Atomicity, Consistency, Isolation, Durability) of transactions, thus ensuring reliable and consistent database operations even in cases of system failures or errors .

Relational databases, such as MySQL and Oracle, store data in tabular form using schemas that define data structure. They use SQL for data retrieval and manipulation, reliant on tables and relations between them. Non-relational databases (NoSQL), like MongoDB, store data without a fixed structure, using formats like key-value pairs or documents. They are more flexible in terms of data retrieval as they do not require strict adherence to schemas, making them suitable for unstructured or semi-structured data .

Constraints in SQL are essential for maintaining data quality and integrity by enforcing rules at the data column level. Constraints like NOT NULL prevent null values in specific columns, ensuring essential information is always present. UNIQUE constraints ensure that all values in a column are different, preserving data uniqueness. PRIMARY KEY combines NOT NULL and UNIQUE ensuring a unique identifier for table rows, and FOREIGN KEY constraints maintain referential integrity by linking data between tables. DEFAULT provides default values for columns, CHECK constraints validate data based on conditions. These mechanisms ensure consistency, accuracy, and reliability of data throughout database operations .

JOIN operations in SQL are significant as they allow for retrieving data from multiple tables based on related columns, essentially combining them into a single result set. This feature is crucial for relational databases, which normalize data into different tables to ensure data integrity and reduce redundancy. JOINS, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN, enable the execution of complex queries efficiently by establishing relationships between tables based on key columns. Using JOINS helps in leveraging the relational model to perform comprehensive data analyses, view integrated data across tables, and harness the full power of descriptive queries in relational databases .

You might also like