SlideShare a Scribd company logo
1 introduction to my sql
   To log in to mysql monitor:
     Mysql –u root
   MySQL monitor




   To log out, just type exit or quit
1 introduction to my sql
   Selecting a Database
     Mysql> show databases;
   Selecting a Database
     Mysql> use guitars;
   If you forget which database is selected use
    the select database(); statement
 Mysql> create database guitars;
 Mysql> use guitars;
 Mysql> select database();
   Mysql> drop database guitars;
1 introduction to my sql
1 introduction to my sql
   The table creation command requires
     Name of the table
     Names of fields
     Definitions for each field
   The generic table creation syntax is:
   CREATE TABLE table_name (column_name
    column_type);
 The table name is up to you of course, but
  should be a name that reflects the usage of the
  table.
 For example, if you have a table that holds the
  inventory of a grocery store, you wouldn't name
  the table s. You would probably name it
  something like grocery_inventory.
 Similarly, the field names you select should be as
  concise as possible and relevant to the function
  they serve and the data they hold. For example,
  you might call a field holding the name of an
  item item_name, not n.
mysql> CREATE TABLE grocery_inventory (
 -> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> item_name VARCHAR (50) NOT NULL,
-> item_desc TEXT,
-> item_price FLOAT NOT NULL,
-> curr_qty INT NOT NULL -> );
Query OK, 0 rows affected (0.02 sec)
 The MySQL server responds with Query OK
   each time a command, regardless of type, is
   successful.
 INSERT INTO table_name (column list) VALUES
  (column values);
 Within the parenthetical list of values, you must enclose
  strings within quotation marks.
 The SQL standard is single quotes, but MySQL enables
  the usage of either single or double quotes. Remember
  to escape the type of quotation mark used, if it's within
  the string itself.
 Integers do not require quotation marks around them.
   Two main parts of the INSERT statement:
     Column list
     Value List
   Only the value list is actually required, but if
    you omit the column list, you must
    specifically provide for each column in your
    value list in the exact order.
   A statement with all columns named:

   INSERT INTO grocery_inventory (id, item_name, item_desc,
    item_price, curr_qty) VALUES ('1', 'Apples', 'Beautiful, ripe
    apples.', '0.25', 1000);
   A statement that uses all columns but does
    not explicitly name them:

   INSERT INTO grocery_inventory VALUES ('2', 'Bunches of
    Grapes', 'Seedless grapes.', '2.99', 500);
mysql> INSERT INTO grocery_inventory
-> (id, item_name, item_desc, item_price, curr_qty)
-> VALUES
 -> (1, 'Apples', 'Beautiful, ripe apples.', 0.25, 1000);
 Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO grocery_inventory VALUES (2, 'Bunches
  of Grapes',
-> 'Seedless grapes.', 2.99, 500);
 Query OK, 1 row affected (0.01 sec)
   Now for some more interesting methods of using INSERT.
    Because id is an auto-incrementing integer, you don't have
    to put it in your value list.
    However, if there's a value you specifically don't want to list
    (such as id), you then must list the remaining columns in use.
    For example, the following statement does not list the
    columns and also does not give a value for id, and it produces
    an error:

   mysql> INSERT INTO grocery_inventory VALUES ->
    ('Bottled Water (6-pack)', '500ml spring water.', 2.29, 250);
    ERROR 1136: Column count doesn't match value count at
    row 1
 Because you didn't list any columns, MySQL
  expects all of them to be in the value list,
  causing an error on the previous statement.
 If the goal was to let MySQL do the work for
  you by auto-incrementing the id field, you
  could use either of these statements:
   INSERT INTO grocery_inventory
    (item_name, item_desc, item_price,
    curr_qty) VALUES ('Bottled Water (6-pack)',
    '500ml spring water.', '2.29', 250);
   A statement that uses all columns, but does
    not explicitly name them and indicates a
    NULL enTRy for id (so one is filled in for you):

   INSERT INTO grocery_inventory VALUES
    ('NULL', 'Bottled Water (12-pack)', '500ml
    spring water.', 4.49, 500);
 SELECT is the SQL command used to retrieve
  records from your tables.
 This command syntax can be totally
  simplistic or very complicated, depending on
  which fields you want to select, whether you
  want to select from multiple tables, and what
  conditions you plan to impose.
 SELECT expressions_and_columns
 FROM table_name
 [WHERE some_condition_is_true]
 [ORDER BY some_column [ASC | DESC]]
  [LIMIT offset, rows]
 * stands for everything.
 So, to select everything (all rows, all
  columns) from the grocery_inventory table,
  your SQL statement would be:
 SELECT * FROM grocery_inventory;
   If you only want to select specific columns,
    replace the * with the names of the columns,
    separated by commas.
 Results of SELECT queries are ordered as
  they were inserted into the table and
  shouldn't be relied on as a meaningful
  ordering system.
 If you want to order results a specific way,
  such as by date, ID, name, and so on, specify
  your requirements using the ORDER BY
  clause.
1 introduction to my sql
1 introduction to my sql
 When selecting results from a table without
  specifying a sort order, the results may or may
  not be ordered by their key value.
 This occurs because MySQL reuses the space
  taken up by previously deleted rows.
 In other words, if you add records with ID values
  of 1 through 5, delete the record with ID number
  4, and then add another record (ID number 6),
  the records might appear in the table in this
  order: 1, 2, 3, 6, 5.
   The default sorting of ORDER BY is
    ascending (ASC); strings sort from A to Z,
    integers start at 0, dates sort from oldest to
    newest. You can also specify a descending
    sort, using DESC:
1 introduction to my sql
 You can use the LIMIT clause to return only a
  certain number of records from your SELECT
  query result.
 There are two requirements when using the
  LIMIT clause:
     the offset and the number of rows. The offset is
      the starting position,
     and the number of rows should be self-
      explanatory.
 Suppose you had more than two or three
  records in the grocery_inventory table, and
  you wanted to select the ID, name, and
  quantity of the first two, ordered by curr_qty.
 In other words, you want to select the two
  items with the least inventory. The following
  single-parameter limit will start at the 0
  (zero) position and go to the second record:
1 introduction to my sql
 You have learned numerous ways to retrieve
  particular columns from your tables but not
  specific rows.
 This is when the WHERE clause comes in to
  play. From the example SELECT syntax, you
  see that WHERE is used to specify a particular
  condition:
 SELECT expressions_and_columns FROM
  table_name
 [WHERE some_condition_is_true]
Operator             Meaning
   =       Equal To
   !=      Not equal to
  <=       Less than or Equal to
   <       Less Than
  >=       Greater than or equal to
   >       Greater than
   There's also a handy operator called BETWEEN, which is
    useful with integer or data comparisons because it searches
    for results between a minimum and maximum value. For
    example:
   Other operators include logical operators, which
    enable you to use multiple comparisons within
    your WHERE clause.
   The basic logical operators are AND and OR.
   When using AND, all comparisons in the clause
    must be true to retrieve results, whereas
   Using OR allows a minimum of one comparison
    to be true.
    Also, you can use the IN operator to specify a
    list of items that you want to match.
 You were introduced to matching strings
  within a WHERE clause by using = or !=, but
  there's another useful operator for the
  WHERE clause when comparing strings:
 The LIKE operator. This operator uses two
  characters as wildcards in pattern matching:
     % Matches multiple characters
     Matches exactly one character
   For example, if you want to find records in
    the grocery_inventory table where the first
    name of the item starts with the letter A, you
    would use
 You're not limited to selecting only one table
  at a time. That would certainly make
  application programming a long and tedious
  task! When you select from more than one
  table in one SELECT statement, you are
  really joining the tables together.
 Suppose you have two tables: fruit and color.
  You can select all rows from each of the two
  tables by using two separate SELECT
  statements:
1 introduction to my sql
 When you want to select from both tables at
  once, there are a few differences in the
  syntax of the SELECT statement.
 First, you must ensure that all the tables
  you're using in your query appear in the
  FROM clause of the SELECT statement.
 Using the fruit and color example, if you
  simply want to select all columns and rows
  from both tables, you might think you would
  use the following SELECT statement:
1 introduction to my sql
   When you select from multiple tables, you must build
    proper WHERE clauses to ensure that you really get
    what you want.
   In the case of the fruit and color tables, what you
    really want is to see the fruitname and colorname
    records from these two tables where the IDs of each
    match up.
   This brings us to the next nuance of the query how to
    indicate exactly which field you want when the fields
    are named the same in both tables!
   Simply, you append the table name to the field name,
    like this:
   tablename.fieldname
1 introduction to my sql
   UPDATE is the SQL command used to
    modify the contents of one or more columns
    in an existing record or set of records. The
    most basic UPDATE syntax looks like this:

 UPDATE table_name SET column1='new
  value', column2='new value2‘
 [WHERE some_condition_is_true]
1 introduction to my sql
 You must be careful and use a condition when
  updating a table, unless you really intend to
  change all the columns for all records to the
  same value.
 For the sake of argument, assume that "grape"
  is spelled incorrectly in the table, and you want
  to use UPDATE to correct this mistake. This
  query would have horrible results:
 mysql> UPDATE fruit SET fruit_name = 'grape';
  Query OK, 4 rows affected (0.00 sec) Rows
  matched: 4 Changed: 4 Warnings: 0
1 introduction to my sql
 Assume your fruit table has not been
  completely filled with grapes but instead
  contains four records, one with a spelling
  mistake (grappe instead of grape).
 The UPDATE statement to fix the spelling
  mistake would be
 mysql> UPDATE fruit SET fruit_name =
  'grape' WHERE fruit_name = 'grappe';
1 introduction to my sql
 When someone purchases a product, the
  inventory table should be updated
  accordingly. However, you won't know
  exactly what number to enter in the curr_qty
  column, just that you sold one. In this case,
  use the current value of the column and
  subtract 1:
 mysql> UPDATE grocery_inventory SET
  curr_qty = curr_qty - 1 WHERE id = 1;
1 introduction to my sql
 Another method for modifying records is to use
  the REPLACE command, which is remarkably
  similar to the INSERT command.
 REPLACE INTO table_name (column list)
  VALUES (column values);
 The REPLACE statement works like this: If the
  record you are inserting into the table contains a
  primary key value that matches a record already
  in the table, the record in the table will be
  deleted and the new record inserted in its place.
 Using the grocery_inventory table, the
  following command replaces the entry for
  Apples:
 mysql> REPLACE INTO grocery_inventory
  VALUES -> (1, 'Granny Smith Apples',
  'Sweet!', '0.50', 1000);
 Query OK, 2 rows affected (0.00 sec)
1 introduction to my sql
1 introduction to my sql
 The basic DELETE syntax is
 DELETE FROM table_name
 [WHERE some_condition_is_true] [LIMIT rows]
 Notice there is no column specification used in
  the DELETE commandwhen you use DELETE,
  the entire record is removed.
 You might recall the fiasco earlier in this chapter,
  regarding grapes in the fruit table, when
  updating a table without specifying a condition
  caused all records to be updated.
 You must be similarly careful when using
  DELETE.
 Assuming the following structure and data in
  a table called fruit:
 mysql> SELECT * FROM fruit;
 mysql> DELETE FROM fruit;
  You can always verify the deletion by
  attempting to SELECT data from the table. If
  you issued this command after removing all
  the records:
 mysql> SELECT * FROM fruit;
 Empty set (0.00 sec)
 A conditional DELETE statement, just like a
  conditional SELECT or UPDATE statement, means
  you are using WHERE clauses to match specific
  records.
 You have the full range of comparison and logical
  operators available to you, so you can pick and choose
  which records you want to delete.
 A prime example would be to remove all records for
  rotten fruit from the fruit table:
 mysql> DELETE FROM fruit WHERE status =
  'rotten';
 DELETE FROM table_name
 [WHERE some_condition_is_true]
 [ORDER BY some_column [ASC | DESC]]
  [LIMIT rows]
   To remove the oldest record, first use ORDER
    BY to sort the results appropriately, and then
    use LIMIT to remove just one record:
1 introduction to my sql
1 introduction to my sql

More Related Content

PDF
SQL JOINS
Swapnali Pawar
 
PPTX
Sql slid
pacatarpit
 
DOCX
SQL report
Ahmad Zahid
 
PPTX
SQL Tutorial for Beginners
Abdelhay Shafi
 
PPT
MY SQL
sundar
 
DOCX
Query
Raj Devaraj
 
PDF
Database Management System 1
Swapnali Pawar
 
PPT
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
SQL JOINS
Swapnali Pawar
 
Sql slid
pacatarpit
 
SQL report
Ahmad Zahid
 
SQL Tutorial for Beginners
Abdelhay Shafi
 
MY SQL
sundar
 
Database Management System 1
Swapnali Pawar
 
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 

What's hot (19)

PPTX
SQL
Shyam Khant
 
PPTX
06.01 sql select distinct
Bishal Ghimire
 
PPTX
MULTIPLE TABLES
ASHABOOPATHY
 
PPTX
SQL UNION
Ritwik Das
 
PPTX
Inner join and outer join
Nargis Ehsan
 
PPTX
MySQL JOIN & UNION
Jamshid Hashimi
 
PPTX
Interacting with Oracle Database
Chhom Karath
 
PPT
Advanced Sql Training
bixxman
 
PPT
SQL Joinning.Database
Umme habiba
 
PPTX
Oracle: Joins
DataminingTools Inc
 
PDF
Mysql cheatsheet
Adolfo Nasol
 
PDF
Fill series. Data validation. Excel Tutorial
Ilgar Zarbaliyev
 
PPSX
Join query
Waqar Ali
 
PPTX
Joins in SQL
Pooja Dixit
 
PPTX
SQL Server Learning Drive
TechandMate
 
PDF
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Prashant Kumar
 
PPTX
Sql clauses by Manan Pasricha
MananPasricha
 
PPT
Join sql
Vikas Gupta
 
PPTX
SQL JOIN
Ritwik Das
 
06.01 sql select distinct
Bishal Ghimire
 
MULTIPLE TABLES
ASHABOOPATHY
 
SQL UNION
Ritwik Das
 
Inner join and outer join
Nargis Ehsan
 
MySQL JOIN & UNION
Jamshid Hashimi
 
Interacting with Oracle Database
Chhom Karath
 
Advanced Sql Training
bixxman
 
SQL Joinning.Database
Umme habiba
 
Oracle: Joins
DataminingTools Inc
 
Mysql cheatsheet
Adolfo Nasol
 
Fill series. Data validation. Excel Tutorial
Ilgar Zarbaliyev
 
Join query
Waqar Ali
 
Joins in SQL
Pooja Dixit
 
SQL Server Learning Drive
TechandMate
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Prashant Kumar
 
Sql clauses by Manan Pasricha
MananPasricha
 
Join sql
Vikas Gupta
 
SQL JOIN
Ritwik Das
 
Ad

Viewers also liked (9)

PPTX
Mysql:Operators
DataminingTools Inc
 
PPTX
MySQL Data types
Kaveen Prathibha Kumarasinghe
 
PDF
MySQL For Oracle Developers
Ronald Bradford
 
PDF
MySQL for beginners
Saeid Zebardast
 
PPT
MYSQL.ppt
webhostingguy
 
PPS
Introduction to Mysql
Tushar Chauhan
 
PDF
Introduction to MySQL
Giuseppe Maxia
 
PPT
MySql slides (ppt)
webhostingguy
 
PPT
MySQL Atchitecture and Concepts
Tuyen Vuong
 
Mysql:Operators
DataminingTools Inc
 
MySQL For Oracle Developers
Ronald Bradford
 
MySQL for beginners
Saeid Zebardast
 
MYSQL.ppt
webhostingguy
 
Introduction to Mysql
Tushar Chauhan
 
Introduction to MySQL
Giuseppe Maxia
 
MySql slides (ppt)
webhostingguy
 
MySQL Atchitecture and Concepts
Tuyen Vuong
 
Ad

Similar to 1 introduction to my sql (20)

PPTX
Sql
Aman Lalpuria
 
PPTX
DATA BASE || INTRODUCTION OF DATABASE \\ SQL 2018
teachersduniya.com
 
PPTX
ADV Powepoint 3 Lec.pptx
ArjayBalberan1
 
PPTX
Database Overview
Livares Technologies Pvt Ltd
 
PDF
Bt0075 rdbms with mysql 2
Techglyphs
 
PDF
full detailled SQL notesquestion bank (1).pdf
yvpachorib23
 
PDF
Introduction to MySQL and introduction to basic queries
anishacotta2
 
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
PPT
Mysql 120831075600-phpapp01
sagaroceanic11
 
PPT
DBMS-SQL-Commands-BBA-4-Sem-1-PanjabUniversity.ppt
NishaGupta92113
 
PPT
SQL Presentation-1 (structured query language)
renodet116
 
DOC
Learn sql queries
Sanjay Mago
 
PDF
MySQL Cheat Sheet & Quick Referenece.pdf
vaibhavar253
 
PPTX
Introduction To STRUCTURED QUERY LANGUAGE (PART_1).pptx
adnanashraf794146
 
PPTX
Lesson 2_Working_with_Tables_and_SQL_Commands.pptx
quantumlearnai
 
DOC
Complete Sql Server querries
Ibrahim Jutt
 
PDF
Sql
satu2412
 
DATA BASE || INTRODUCTION OF DATABASE \\ SQL 2018
teachersduniya.com
 
ADV Powepoint 3 Lec.pptx
ArjayBalberan1
 
Database Overview
Livares Technologies Pvt Ltd
 
Bt0075 rdbms with mysql 2
Techglyphs
 
full detailled SQL notesquestion bank (1).pdf
yvpachorib23
 
Introduction to MySQL and introduction to basic queries
anishacotta2
 
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
Mysql 120831075600-phpapp01
sagaroceanic11
 
DBMS-SQL-Commands-BBA-4-Sem-1-PanjabUniversity.ppt
NishaGupta92113
 
SQL Presentation-1 (structured query language)
renodet116
 
Learn sql queries
Sanjay Mago
 
MySQL Cheat Sheet & Quick Referenece.pdf
vaibhavar253
 
Introduction To STRUCTURED QUERY LANGUAGE (PART_1).pptx
adnanashraf794146
 
Lesson 2_Working_with_Tables_and_SQL_Commands.pptx
quantumlearnai
 
Complete Sql Server querries
Ibrahim Jutt
 

More from Prof. Erwin Globio (20)

PPT
Embedded System Presentation
Prof. Erwin Globio
 
PDF
BSCS | BSIT Thesis Guidelines
Prof. Erwin Globio
 
PPT
Internet of Things
Prof. Erwin Globio
 
PPTX
Networking Trends
Prof. Erwin Globio
 
PPTX
Sq lite presentation
Prof. Erwin Globio
 
PDF
Ethics for IT Professionals
Prof. Erwin Globio
 
PDF
Cisco Router Basic Configuration
Prof. Erwin Globio
 
PPTX
Introduction to iOS Apps Development
Prof. Erwin Globio
 
PPTX
Cloud Computing Latest
Prof. Erwin Globio
 
PPT
Introduction to Android Development Latest
Prof. Erwin Globio
 
PPTX
iOS Apps Development (SQLite Tutorial Part 2)
Prof. Erwin Globio
 
PPTX
iOS Apps Development (SQLite Tutorial Part 1)
Prof. Erwin Globio
 
PDF
A tutorial on C++ Programming
Prof. Erwin Globio
 
PDF
Overview of C Language
Prof. Erwin Globio
 
PDF
Introduction to Computer Programming
Prof. Erwin Globio
 
PPTX
Android Fragments
Prof. Erwin Globio
 
PPTX
Solutions to Common Android Problems
Prof. Erwin Globio
 
PDF
Android Development Tools and Installation
Prof. Erwin Globio
 
PDF
Java Collections Tutorials
Prof. Erwin Globio
 
PDF
Action Bar in Android
Prof. Erwin Globio
 
Embedded System Presentation
Prof. Erwin Globio
 
BSCS | BSIT Thesis Guidelines
Prof. Erwin Globio
 
Internet of Things
Prof. Erwin Globio
 
Networking Trends
Prof. Erwin Globio
 
Sq lite presentation
Prof. Erwin Globio
 
Ethics for IT Professionals
Prof. Erwin Globio
 
Cisco Router Basic Configuration
Prof. Erwin Globio
 
Introduction to iOS Apps Development
Prof. Erwin Globio
 
Cloud Computing Latest
Prof. Erwin Globio
 
Introduction to Android Development Latest
Prof. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 2)
Prof. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 1)
Prof. Erwin Globio
 
A tutorial on C++ Programming
Prof. Erwin Globio
 
Overview of C Language
Prof. Erwin Globio
 
Introduction to Computer Programming
Prof. Erwin Globio
 
Android Fragments
Prof. Erwin Globio
 
Solutions to Common Android Problems
Prof. Erwin Globio
 
Android Development Tools and Installation
Prof. Erwin Globio
 
Java Collections Tutorials
Prof. Erwin Globio
 
Action Bar in Android
Prof. Erwin Globio
 

Recently uploaded (20)

PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
MariellaTBesana
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
MariellaTBesana
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
Landforms and landscapes data surprise preview
jpinnuck
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 

1 introduction to my sql

  • 2. To log in to mysql monitor:  Mysql –u root  MySQL monitor  To log out, just type exit or quit
  • 4. Selecting a Database  Mysql> show databases;  Selecting a Database  Mysql> use guitars;  If you forget which database is selected use the select database(); statement
  • 5.  Mysql> create database guitars;  Mysql> use guitars;  Mysql> select database();
  • 6. Mysql> drop database guitars;
  • 9. The table creation command requires  Name of the table  Names of fields  Definitions for each field  The generic table creation syntax is:  CREATE TABLE table_name (column_name column_type);
  • 10.  The table name is up to you of course, but should be a name that reflects the usage of the table.  For example, if you have a table that holds the inventory of a grocery store, you wouldn't name the table s. You would probably name it something like grocery_inventory.  Similarly, the field names you select should be as concise as possible and relevant to the function they serve and the data they hold. For example, you might call a field holding the name of an item item_name, not n.
  • 11. mysql> CREATE TABLE grocery_inventory ( -> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, -> item_name VARCHAR (50) NOT NULL, -> item_desc TEXT, -> item_price FLOAT NOT NULL, -> curr_qty INT NOT NULL -> ); Query OK, 0 rows affected (0.02 sec)  The MySQL server responds with Query OK each time a command, regardless of type, is successful.
  • 12.  INSERT INTO table_name (column list) VALUES (column values);  Within the parenthetical list of values, you must enclose strings within quotation marks.  The SQL standard is single quotes, but MySQL enables the usage of either single or double quotes. Remember to escape the type of quotation mark used, if it's within the string itself.  Integers do not require quotation marks around them.
  • 13. Two main parts of the INSERT statement:  Column list  Value List  Only the value list is actually required, but if you omit the column list, you must specifically provide for each column in your value list in the exact order.
  • 14. A statement with all columns named:  INSERT INTO grocery_inventory (id, item_name, item_desc, item_price, curr_qty) VALUES ('1', 'Apples', 'Beautiful, ripe apples.', '0.25', 1000);  A statement that uses all columns but does not explicitly name them:  INSERT INTO grocery_inventory VALUES ('2', 'Bunches of Grapes', 'Seedless grapes.', '2.99', 500);
  • 15. mysql> INSERT INTO grocery_inventory -> (id, item_name, item_desc, item_price, curr_qty) -> VALUES -> (1, 'Apples', 'Beautiful, ripe apples.', 0.25, 1000);  Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO grocery_inventory VALUES (2, 'Bunches of Grapes', -> 'Seedless grapes.', 2.99, 500);  Query OK, 1 row affected (0.01 sec)
  • 16. Now for some more interesting methods of using INSERT. Because id is an auto-incrementing integer, you don't have to put it in your value list.  However, if there's a value you specifically don't want to list (such as id), you then must list the remaining columns in use. For example, the following statement does not list the columns and also does not give a value for id, and it produces an error:  mysql> INSERT INTO grocery_inventory VALUES -> ('Bottled Water (6-pack)', '500ml spring water.', 2.29, 250); ERROR 1136: Column count doesn't match value count at row 1
  • 17.  Because you didn't list any columns, MySQL expects all of them to be in the value list, causing an error on the previous statement.  If the goal was to let MySQL do the work for you by auto-incrementing the id field, you could use either of these statements:
  • 18. INSERT INTO grocery_inventory (item_name, item_desc, item_price, curr_qty) VALUES ('Bottled Water (6-pack)', '500ml spring water.', '2.29', 250);
  • 19. A statement that uses all columns, but does not explicitly name them and indicates a NULL enTRy for id (so one is filled in for you):  INSERT INTO grocery_inventory VALUES ('NULL', 'Bottled Water (12-pack)', '500ml spring water.', 4.49, 500);
  • 20.  SELECT is the SQL command used to retrieve records from your tables.  This command syntax can be totally simplistic or very complicated, depending on which fields you want to select, whether you want to select from multiple tables, and what conditions you plan to impose.
  • 21.  SELECT expressions_and_columns  FROM table_name  [WHERE some_condition_is_true]  [ORDER BY some_column [ASC | DESC]] [LIMIT offset, rows]
  • 22.  * stands for everything.  So, to select everything (all rows, all columns) from the grocery_inventory table, your SQL statement would be:  SELECT * FROM grocery_inventory;
  • 23. If you only want to select specific columns, replace the * with the names of the columns, separated by commas.
  • 24.  Results of SELECT queries are ordered as they were inserted into the table and shouldn't be relied on as a meaningful ordering system.  If you want to order results a specific way, such as by date, ID, name, and so on, specify your requirements using the ORDER BY clause.
  • 27.  When selecting results from a table without specifying a sort order, the results may or may not be ordered by their key value.  This occurs because MySQL reuses the space taken up by previously deleted rows.  In other words, if you add records with ID values of 1 through 5, delete the record with ID number 4, and then add another record (ID number 6), the records might appear in the table in this order: 1, 2, 3, 6, 5.
  • 28. The default sorting of ORDER BY is ascending (ASC); strings sort from A to Z, integers start at 0, dates sort from oldest to newest. You can also specify a descending sort, using DESC:
  • 30.  You can use the LIMIT clause to return only a certain number of records from your SELECT query result.  There are two requirements when using the LIMIT clause:  the offset and the number of rows. The offset is the starting position,  and the number of rows should be self- explanatory.
  • 31.  Suppose you had more than two or three records in the grocery_inventory table, and you wanted to select the ID, name, and quantity of the first two, ordered by curr_qty.  In other words, you want to select the two items with the least inventory. The following single-parameter limit will start at the 0 (zero) position and go to the second record:
  • 33.  You have learned numerous ways to retrieve particular columns from your tables but not specific rows.  This is when the WHERE clause comes in to play. From the example SELECT syntax, you see that WHERE is used to specify a particular condition:  SELECT expressions_and_columns FROM table_name  [WHERE some_condition_is_true]
  • 34. Operator Meaning = Equal To != Not equal to <= Less than or Equal to < Less Than >= Greater than or equal to > Greater than
  • 35. There's also a handy operator called BETWEEN, which is useful with integer or data comparisons because it searches for results between a minimum and maximum value. For example:
  • 36. Other operators include logical operators, which enable you to use multiple comparisons within your WHERE clause.  The basic logical operators are AND and OR.  When using AND, all comparisons in the clause must be true to retrieve results, whereas  Using OR allows a minimum of one comparison to be true.  Also, you can use the IN operator to specify a list of items that you want to match.
  • 37.  You were introduced to matching strings within a WHERE clause by using = or !=, but there's another useful operator for the WHERE clause when comparing strings:  The LIKE operator. This operator uses two characters as wildcards in pattern matching:  % Matches multiple characters  Matches exactly one character
  • 38. For example, if you want to find records in the grocery_inventory table where the first name of the item starts with the letter A, you would use
  • 39.  You're not limited to selecting only one table at a time. That would certainly make application programming a long and tedious task! When you select from more than one table in one SELECT statement, you are really joining the tables together.  Suppose you have two tables: fruit and color. You can select all rows from each of the two tables by using two separate SELECT statements:
  • 41.  When you want to select from both tables at once, there are a few differences in the syntax of the SELECT statement.  First, you must ensure that all the tables you're using in your query appear in the FROM clause of the SELECT statement.  Using the fruit and color example, if you simply want to select all columns and rows from both tables, you might think you would use the following SELECT statement:
  • 43. When you select from multiple tables, you must build proper WHERE clauses to ensure that you really get what you want.  In the case of the fruit and color tables, what you really want is to see the fruitname and colorname records from these two tables where the IDs of each match up.  This brings us to the next nuance of the query how to indicate exactly which field you want when the fields are named the same in both tables!  Simply, you append the table name to the field name, like this:  tablename.fieldname
  • 45. UPDATE is the SQL command used to modify the contents of one or more columns in an existing record or set of records. The most basic UPDATE syntax looks like this:  UPDATE table_name SET column1='new value', column2='new value2‘  [WHERE some_condition_is_true]
  • 47.  You must be careful and use a condition when updating a table, unless you really intend to change all the columns for all records to the same value.  For the sake of argument, assume that "grape" is spelled incorrectly in the table, and you want to use UPDATE to correct this mistake. This query would have horrible results:  mysql> UPDATE fruit SET fruit_name = 'grape'; Query OK, 4 rows affected (0.00 sec) Rows matched: 4 Changed: 4 Warnings: 0
  • 49.  Assume your fruit table has not been completely filled with grapes but instead contains four records, one with a spelling mistake (grappe instead of grape).  The UPDATE statement to fix the spelling mistake would be  mysql> UPDATE fruit SET fruit_name = 'grape' WHERE fruit_name = 'grappe';
  • 51.  When someone purchases a product, the inventory table should be updated accordingly. However, you won't know exactly what number to enter in the curr_qty column, just that you sold one. In this case, use the current value of the column and subtract 1:  mysql> UPDATE grocery_inventory SET curr_qty = curr_qty - 1 WHERE id = 1;
  • 53.  Another method for modifying records is to use the REPLACE command, which is remarkably similar to the INSERT command.  REPLACE INTO table_name (column list) VALUES (column values);  The REPLACE statement works like this: If the record you are inserting into the table contains a primary key value that matches a record already in the table, the record in the table will be deleted and the new record inserted in its place.
  • 54.  Using the grocery_inventory table, the following command replaces the entry for Apples:  mysql> REPLACE INTO grocery_inventory VALUES -> (1, 'Granny Smith Apples', 'Sweet!', '0.50', 1000);  Query OK, 2 rows affected (0.00 sec)
  • 57.  The basic DELETE syntax is  DELETE FROM table_name  [WHERE some_condition_is_true] [LIMIT rows]  Notice there is no column specification used in the DELETE commandwhen you use DELETE, the entire record is removed.  You might recall the fiasco earlier in this chapter, regarding grapes in the fruit table, when updating a table without specifying a condition caused all records to be updated.  You must be similarly careful when using DELETE.
  • 58.  Assuming the following structure and data in a table called fruit:  mysql> SELECT * FROM fruit;
  • 59.  mysql> DELETE FROM fruit; You can always verify the deletion by attempting to SELECT data from the table. If you issued this command after removing all the records:  mysql> SELECT * FROM fruit;  Empty set (0.00 sec)
  • 60.  A conditional DELETE statement, just like a conditional SELECT or UPDATE statement, means you are using WHERE clauses to match specific records.  You have the full range of comparison and logical operators available to you, so you can pick and choose which records you want to delete.  A prime example would be to remove all records for rotten fruit from the fruit table:  mysql> DELETE FROM fruit WHERE status = 'rotten';
  • 61.  DELETE FROM table_name  [WHERE some_condition_is_true]  [ORDER BY some_column [ASC | DESC]] [LIMIT rows]
  • 62. To remove the oldest record, first use ORDER BY to sort the results appropriately, and then use LIMIT to remove just one record: