My SQL-Part-1
My SQL-Part-1
Vidhya Vibha
About Me and
My Institute
Scope
Career Scope
Database Administrator
Database Analyst
Learning Path
Perform Perform intricate queries on database records with filters and groupings
Create Create relationships between tables using primary and foreign keys
When you are executing an SQL command for any RDBMS, the
system determines the best way to carry out your request and SQL
engine figures out how to interpret the task.
There are various components included in the process. These
components are Query Dispatcher, Optimization Engines, Classic
Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle
logical files.
What is a Database Table?
Scientist First Last Y.O.B Country
ID Name Name
A table is a collection of related data
1 Sir Venkata Raman 1888 India
entries, and it consists of columns and
Chandrasekhara
rows.
2 Homi Jehangir Bhabha 1909 India
4
A column holds specific information
about every record in the table.
SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
Types of SQL Commands
.); If you are adding values for all the columns of the table, you do not
need to specify the column names in the SQL query. However, make
INSERT INTO table_name sure the order of the values is in the same order as the columns in
the table.
VALUES (value1, value2, value3, .. Example for staff table
.); INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
SQL DROP or DELETE Table
Syntax Description
DROP [TEMPORARY] TABLE [IF The SQL DROP TABLE statement is used to
EXISTS] tbl_name [, remove a table definition and all data,
tbl_name] ... [RESTRICT | indexes, triggers, constraints, and permission
CASCADE] specifications for that table.
DROP TABLE removes one or more tables.
TRUNCATE TABLE
Syntax Description
TRUNCATE [TABLE] tbl_name The MySQL TRUNCATE TABLE statement allows
you to delete all data in a table.
Logically, the TRUNCATE TABLE statement is like
a DELETE statement without a WHERE clause that
deletes all rows from a table, or a sequence of
DROP TABLE and CREATE TABLE statements.
However, the TRUNCATE TABLE statement is
more efficient than the DELETE statement because
it drops and recreates the table instead of deleting
rows one by one.
SELECT statement
Syntax Description
SELECT select_list FROM table_name; SELECT is used to retrieve rows selected from
one or more tables.
SELECT * FROM table_name;
When executing the SELECT statement,
SELECT column1, column2, ...
MySQL evaluates the FROM clause before the
FROM table_name; SELECT clause.
Use the SELECT * to select data from all
columns of a table.
Use the SELECT statement to select data from a
table.
Select Statement
SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_NO_CACHE]
[SQL_CALC_FOUND_ROWS] select_expr [, select_expr] ... [into_option] [FROM
table_references [PARTITION partition_list]] [WHERE where_condition] [GROUP
BY {col_name | expr | position}, ... [WITH ROLLUP]] [HAVING where_condition]
[WINDOW window_name AS (window_spec) [, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}] [into_option] [FOR
{UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED] |
LOCK IN SHARE MODE] [into_option] into_option: { INTO OUTFILE 'file_name'
[CHARACTER SET charset_name] export_options | INTO DUMPFILE 'file_name' |
INTO var_name [, var_name] ... }
WHERE Clause
Syntax Description
SELECT select_list FROM table_name The WHERE clause is used to filter records.
It is used to extract only those records that
WHERE search_condition;
fulfill a specified condition.
SELECT column1, column2, ...
You can specify a condition using comparison
FROM table_name
or logical operators like >, =,< etc.
WHERE condition;
UPDATE Query
UPDATE table_name The SQL UPDATE Query is used to
SET column1 = value1, colu modify the existing records in a
mn2 = value2, ... table.
WHERE condition; You can use WHERE clause with
UPDATE query to update selected
rows, otherwise all the rows would
be affected.
Syntax The SQL DELETE Query is used to
DELETE FROM table_name WHERE delete the existing records from a
condition; table.
Example You can use WHERE clause with
DELETE FROM Student WHERE DELETE query to delete selected
StudentId = 4; rows, otherwise all the records
would be deleted.
DELETE Statement
SQL LIKE Clause / SQL LIKE Operator
The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There
are two wildcards used in conjunction with the LIKE operator:
SELECT column1, column2, ... The percent sign (%)
FROM table_name The underscore (_)
WHERE columnN LIKE pattern; The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations.
WHERE StudentName LIKE 'a%' Finds any values that start with "a"
WHERE StudentName LIKE '%a' Finds any values that end with "a"
WHERE StudentName LIKE '%or%' Finds any values that have "or" in any position
WHERE StudentName LIKE '_r%' Finds any values that have "r" in the second position
WHERE StudentName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length
WHERE StudentName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length
WHERE StudentName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
SQL has many built-in functions for performing processing on string or numeric data. Following is the list of all useful SQL
built-in functions
SQL COUNT Function - The SQL COUNT aggregate function is used to count the number of rows in a database table.
SQL MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain
column.
SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain
column.
SQL AVG Function - The SQL AVG aggregate function selects the average value for certain table column.
SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric column.
SQL SQRT Functions - This is used to generate a square root of a given number.
SQL RAND Function - This is used to generate a random number using SQL command.
SQL CONCAT Function - This is used to concatenate any string inside any SQL command.
SQL Numeric Functions - Complete list of SQL functions required to manipulate numbers in SQL.
SQL String Functions - Complete list of SQL functions required to manipulate strings in SQL.
SQL Function
SQL Aggregate Functions
• SQL aggregate functions return a single value, calculated from values in a column.
• Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
SQL
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
Function
• SUM() - Returns the sum
SQL Scalar functions
Type
• SQL scalar functions return a single value, based on the input value.
• Useful scalar functions:
• UCASE() - Converts a field to upper case
• LCASE() - Converts a field to lower case
• MID() - Extract characters from a text field
• LEN() - Returns the length of a text field
• ROUND() - Rounds a numeric field to the number of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be displayed
SQL Functions Example
COUNT() Syntax
Description
SELECT COUNT(column_name)
FROM table_name The COUNT() function returns the
WHERE condition;
AVG() Syntax
number of rows that matches a
SELECT AVG(column_name)
specified criterion.
FROM table_name
WHERE condition;
The AVG() function returns the
SUM() Syntax average value of a numeric column.
SELECT SUM(column_name) The SUM() function returns the total
FROM table_name
WHERE condition; sum of a numeric column.
Function Description MySQL comes with the following
NOW() Returns the current date and time data types for storing a date or a
CURDATE() Returns the current date date/time value in the database:
CURTIME()Returns the current time DATE - format YYYY-MM-DD
DATE() Extracts the date part of a date or date/time expression DATETIME - format: YYYY-MM-
EXTRACT() Returns a single part of a date/time DD HH:MI:SS
DATE_ADD() Adds a specified time interval to a date TIMESTAMP - format: HH:MI:SS
DATE_SUB() Subtracts a specified time interval from a date YEAR - format YYYY or YY
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
MONTH(date) Returns the month part for a given date (i.e from 1 -
12).
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ALTER SYNTAX
3) DROP column in table
1) ADD a column in the table
ALTER TABLE table_name
ALTER TABLE table_name DROP COLUMN column_name;
ADD column_name datatype; ... ;
4) RENAME column in table
2) MODIFY column in the table
ALTER TABLE table_name
ALTER TABLE table_name
MODIFY COLUMN column_name datatype; CHANGE COLUMN OldcolumnName NewcolumNname
datatype;
ALIAS SYNTAX
Alias for columns Alias for tables
SELECT column_name AS alias_name SELECT column_name(s)
FROM table_name; FROM table_name AS alias_name;
STRING FUNCTIONS
Length(string): This function returns the length of the string, in bytes
REPLACE(string, from_string, new_string): This function replaces a string or
character(s)
POSITION(substring IN string): This function finds the position of the character
REVERSE(string): This function reverses a string and returns the result
UNQUE CONSTRAINTS
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.