0% found this document useful (0 votes)
8 views6 pages

Essential SQL Commands and Functions

Uploaded by

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

Essential SQL Commands and Functions

Uploaded by

nshrinivas38
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

COMMON QUERIES:

SHOW DATABASES; ;

DROP TABLE table_name;

DROP DATABASE database_name;

SELECT * FROM table_name;


or
SELECT rollno,name FROM students;

DEFAULT - Value get added if not mention ("Eg. column_name INT DEFAULT 25000;")

UNIQUE - Unique value and Null value are allowed (Eg. UNIQUE (email_id) used in
create table)

DISTINCT - Unique Value ([Link] DISTINCT city FROM students;)

WHERE - To apply any condition (Eg. SELECT * FROM students WHERE city="Mumbai";)

AND - To add one more condition (Eg. SELECT * FROM students WHERE city="Mumbai" AND
marks > 80; )

Arithmetic Operators : +,-,*,/,%

Comparison Operators : =,!=,>,>=,,<=

Logical Operators : AND,OR,NOT,BETWEEN,ALL,LIKE,ANY (Eg. SELECT * FROM students


WHERE marks BETWEEN 80 AND 90;)

Bitwise Operators : &(Bitwise AND),|(Bitwise OR)

LIMIT Clause : controls the number of row to be displayed in a table (Eg. SELECT *
FROM students LIMIT 3;)

ASC and DSC : Ascending and descending order (Eg. SELECT * FROM students ORDER BY
city ASC;)

GROUP BY clause : Makes group of city and it also use Aggregate Clause for the
count ([Link] city, COUNT(city) FROM students GROUP BY city;)

GENERAL ORER:

SELECT column(s)
FROM table_name
WHERE condition
GROUP BY column(s)
HAVING condition
ORDER BY column(s) ASC;

Aggregate Function:

COUNT()
MAX()
MIN()
AVG()
SUM()
KEYS:

Primary key - "Unique value are present but null value not allowed"
foreign Key - "Primary key of other table, Duplicate and null value allowed"

CREATE QUERY:

CREATE DATABASES database_name;


USE database_name - "To use the database"

CREATE TABLE table_name(


col_name col_datatype constraints,
col_name col_datatype constraints,
);

INSERT INTO employee


(id,name)
VALUES
(1, "Dheeraj"),
(2, "Varun");

-"To add values in table"

UPDATE students
SET marks = 92
WHERE marks = 12;

-"To Update values in a column"

SET SQL_SAFE_UPDATES = 0; - If any error while using UPDATE to off just add 1 here

DELETE FROM students


WHERE marks<50;

-"To Delete any value from the table"

DELETE FROM students

-"To Delete all value from the table"

FOREIGN KEY (dpt_id) REFERENCES dpt(id)


-"To link two tables"

ON UPDATE CASCADE
ON DELETE CASCADE

-"To make perform update and delete operation simultaneously on both table"

ALTER TABLE mytb


ADD COLUMN age INT;

-"To add column to the table"

ALTER TABLE mytb


DROP COLUMN age;

-"To delete the column"

ALTER TABLE example


RENAME TO mytb;

-"To rename the table"

ALTER TABLE mytb


CHANGE COLUMN id my_id INT;

-"To Rename the Column"

ALTER TABLE mytb


MODIFY name VARCHAR(100);

-"To change the datatype and constraint of the table"

JOINS:

Inner join:

SELECT *
FROM mytb as tb
INNER JOIN mytb1 as tb1
ON [Link] = [Link];

-"Common data (intersection)"

left join:

SELECT *
FROM mytb as tb
LEFT JOIN mytb1 as tb1
ON [Link] = [Link];
-"Left entire data and common data"

Right join:

SELECT *
FROM mytb as tb
RIGHT JOIN mytb1 as tb1
ON [Link] = [Link];

-"Right entire data and common data"

Union join:

SELECT *
FROM mytb as tb
LEFT JOIN mytb1 as tb1
ON [Link] = [Link]
UNION
SELECT *
FROM mytb as tb
RIGHT JOIN mytb1 as tb1
ON [Link] = [Link];

-"combination of left and right data"

left exclusive join:

SELECT *
FROM mytb as tb
LEFT JOIN mytb1 as tb1
ON [Link]=[Link]
WHERE [Link] IS NULL;

-"entire left data without common data"

Right exclusive join:

SELECT *
FROM mytb as tb
RIGHT JOIN mytb1 as tb1 //usin as it is calld alias
ON [Link]=[Link]
WHERE [Link] IS NULL;

-"entire Right data without common data"

Self join:

SELECT *
FROM mytb as tb
JOIN mytb1 as tb1
ON [Link] = [Link];

-"Just like inner join but it is used to compare two table for same kind based on
the similar column they share"

UNION:

SELECT name FROM mytb


UNION
SELECT surr FROM mytb1;

"Give all values of table1 = name column and table1 = surr column all unique"

UNION ALL:

SELECT name FROM mytb


UNION ALL
SELECT surr FROM mytb1;

-"Give all values of table1 = name column and table1 = surr column including
duplicate"

SQL SUB QUERIES:

three ways of writing:


SELECT
FROM
WHERE (mostly used)

WHERE:
SELECT name, marks
FROM students
WHERE marks IN (SELECT marks
FROM students
WHERE marks%2=0);

FROM:
SELECT MAX(marks)
FROM (SELECT * FROM students WHERE city = "Delhi") as temp;

SELECT:

SELECT (SELECT MAX(marks) FROM students), name


FROM students;

-"Can be used but not used mostly"(SELECT)

-"Using query logic in other query and it is used for single query which has only
one specific value not for the whole column value"(SELECT,FROM and WHERE)
MySQL View:

CREATE VIEW viewing AS


SELECT name,rollno,city FROM students;

SELECT * FROM viewing; (any condition can be applied like this


"SELECT * FROM view WHERE marks>90;")

DROP VIEW viewing; (View can be dropped)

-"It decide which data should be visible in a table by creating a virtual view of
the table"

Common questions

Powered by AI

SQL supports several JOIN operations: Inner Join, Left Join, Right Join, Union Join, and exclusive joins like Left Exclusive Join and Right Exclusive Join. An Inner Join returns only the rows with matching values in both tables . A Left Join returns all rows from the left table and matched rows from the right table, with NULLs where no match exists . Conversely, a Right Join returns all rows from the right table and matched rows from the left table . A Union Join combines the sets from the left and right joins . Exclusive Joins like Left Exclusive Join and Right Exclusive Join return rows only from the non-matched portions of the left and right tables respectively .

Subqueries in the WHERE clause are preferable when you need to filter based on an aggerate or a calculated result from another table that cannot be easily joined . They are useful for queries where the filtering condition involves non-correlated data or performing operations like checking for existence or certain conditions among entries of other tables. In contrast, joins are more efficient for combining tables based on direct relationships . Subqueries can offer a more readable structure for nested logic but might perform less efficiently if not optimized properly for complex joins.

The GROUP BY clause in SQL is used to arrange identical data into groups. When combined with aggregate functions, it allows you to perform calculations like sum or count on each group . The HAVING clause is then applied to filter these groups based on a specified condition of the aggregated data, which cannot be done with a standard WHERE clause because WHERE filters rows before aggregation . For example, you might group sales data by region and use HAVING to only display regions with a total sales value above a certain threshold, allowing for advanced data filtering of aggregate results .

The UNIQUE constraint in an SQL database allows distinct or unique values in a column, and it can contain NULL values . On the other hand, a PRIMARY KEY constraint does not allow NULL values and ensures all values in the column are unique, effectively being a combination of NOT NULL and UNIQUE constraints . This makes the PRIMARY KEY more restrictive than the UNIQUE constraint.

A SQL view is a virtual table that is created based on a SELECT query, allowing users to present data from one or multiple tables in a specific format . It does not store the data physically, making it lightweight, and allows users to simplify complex queries by encapsulating them into a single SQL statement . Views are beneficial in cases where you want to present specific information to users without exposing the base tables, enabling both data security and simplified query logic . They are also useful for managing the complexity of database schemas, allowing developers to compartmentalize access and presentation logic.

The SQL DELETE FROM WHERE statement is crucial for removing rows from a table based on specified conditions . The WHERE clause is essential to target specific rows for deletion, preventing the unintended removal of all table data, which would occur if WHERE is omitted. Precautions include ensuring SQL_SAFE_UPDATES is enabled to prevent deletion without a condition and using transaction controls like BEGIN and COMMIT to manage changes that could potentially remove critical data . It's also a good practice to first run a SELECT statement with the same conditions to verify the correct rows will be affected.

The UNION operation in SQL combines the result sets of two or more SELECT queries and automatically eliminates any duplicate records, which can streamline the data for reporting purposes . However, eliminating duplicates involves additional computation, potentially leading to reduced performance . On the other hand, UNION ALL includes all records, preserving duplicates, thus executing faster than UNION because it skips the step of detecting duplicate entries . The decision to use UNION versus UNION ALL should consider the necessity of duplicate elimination against performance needs and the nature of the query requirements.

Aggregate functions in SQL, such as COUNT, MAX, MIN, AVG, and SUM, are used to perform calculations on multiple rows of a table's column and return a single value . They are particularly useful in summarizing large datasets, identifying trends, and making statistical analyses. When combined with the GROUP BY clause, these functions allow you to apply calculations across grouped subsets of data, providing meaningful insights at various aggregation levels (e.g., by categorizing data by a column such as "city"). This enables structured data summaries that can support detailed decision-making processes.

When SQL_SAFE_UPDATES mode is enabled, the SQL UPDATE statement requires a WHERE clause to prevent accidental updates to all rows in a table . When the mode is disabled by setting SQL_SAFE_UPDATES = 0, you can update a table without a WHERE clause, which could lead to changes across all rows in the specified column or columns . This mode provides an additional layer of safety by default, reducing the risk of widespread unintended updates.

To maintain database integrity with foreign keys, several strategies can be employed. Enforcing foreign key constraints ensures that records in the referencing table correspond to valid records in the referenced table, preventing orphan records . Additionally, actions such as ON DELETE CASCADE or ON UPDATE CASCADE can be set up to automatically update or delete dependent records in child tables when changes occur in the parent table . These constraints, alongside proper indexing of columns involved in foreign key relationships, improve both integrity and query performance, ensuring that data across tables remains consistent and reliable.

You might also like