PHP Tutorials
- What is MySqli
- mysql query
- mysql query example
- InnoDB
- mysql column Type
- CRUD Example
- Connection Using Function
- mysql keys
- SELECT
- WHERE
- UPDATE
- Count no of Rows
- ALIAS
- AND, AND & OR
- BETWEEN
- COMPARISON OPERATOR
- DELETE
- DELETE LIMIT
- DISTINCT
- EXISTS
- FROM
- GROUP BY
- HAVING
- IN
- INTERSECT
- IS NULL & IS NOT NULL
- LIKE
- NOT
- ORDER BY
- SELECT LIMIT
- SUBQUERY
- TRUNCATE
- UNION && UNION ALL
- Concat & Group_Concat
- mysql Function
- Mysql Insert Id
- MySql Aggregate Function
- Mysql Join
- JOIN in MySql
- Trigger
- Procedure
- Transaction
- views
- Index
- SQL Injection
- Normalization
- Query Bind
- Interview Questions
Important Link
what is difference between TRUNCATE vs DELETE in SQL
What is transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
COMMIT and ROLLBACK:
These two keywords Commit and Rollback are mainly used for MySQL Transactions.
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SELECT * FROM Customers
WHERE City IN ('Paris','London');
here city is the column name and paris, london is the column data.
BETWEEN Operator
The BETWEEN operator is used to select values within a range.
The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
SQL Aliases
SQL aliases are used to temporarily rename a table or a column heading.
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM table_name;
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name AS alias_name;
why use SQL Aliases
SQL aliases are used to better when two or more tabel column name same. in that case we use for change column name for other name.
Example :
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address
FROM Customers;
Why MySQL is used?
MySQL database server is reliable, fast and very easy to use. This software can be downloaded as freeware and can be downloaded from the internet.
What are Heap tables?
HEAP tables are present in memory and they are used for high speed storage on temporary
basis.
BLOB or TEXT fields are not allowed
Only comparison operators can be used =, <,>, = >,=<
AUTO_INCREMENT is not supported by HEAP tables
Indexes should be NOT NULL
What is the default port for MySQL Server?
The default port for MySQL server is 3306.
What are the advantages of MySQL when compared with Oracle?
MySQL is open source software which is available at any time and has no cost involved.
MySQL is portable
GUI with command prompt.
Administration is supported using MySQL Query Browser
What is the defference between mysql and oracle.
MySQL is open source software which is available at any time and has no cost involved.
MySQL is portable
GUI with command prompt.
Administration is supported using MySQL Query Browser
Differentiate CHAR_LENGTH and LENGTH?
CHAR_LENGTH is character count whereas the LENGTH is byte count. The numbers are same for Latin characters but they are different for Unicode and other encodings.
How to represent ENUMs and SETs internally?
ENUMs and SETs are used to represent powers of two because of storage optimizations.
What is the usage of ENUMs in MySQL?
ENUM is a string object used to specify set of predefined values and that can be used during table creation.
Create table size(name ENUM('Small', 'Medium','Large');
Define REGEXP?
REGEXP is a pattern match in which matches pattern anywhere in the search value.
Difference between CHAR and VARCHAR?
CHAR and VARCHAR types differ in storage and retrieval
CHAR column length is fixed to the length that is declared while creating table. The length value ranges from 1 and 255
When CHAR values are stored then they are right padded using spaces to specific length. Trailing spaces are removed when CHAR values are retrieved.
string types available for column?
The string types are:
SET
BLOB
ENUM
CHAR
TEXT
VARCHAR
How to get current MySQL version?
SELECT VERSION ();
What storage engines are used in MySQL?
Storage engines are called table types and data is stored in files using various techniques.
Technique involves:
Storage mechanism
Locking levels
Indexing
Capabilities and functions.
What are the drivers in MySQL?
Following are the drivers available in MySQL:
PHP Driver
JDBC Driver
ODBC Driver
PYTHON Driver
PERL Driver
RUBY Driver
CAP11PHP Driver
What is the difference between primary key and candidate key?
Every row of a table is identified uniquely by primary key. There is only one primary key for a table.
Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.
What do you mean by % and _ in the LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character in the LIKE statement.
What is the difference between mysql_fetch_array and mysql_fetch_object?
mysql_fetch_array() -Returns a result row as an associated array or a regular array from database.
mysql_fetch_object – Returns a result row as object from database.
What are the different tables present in MySQL?
Total 5 types of tables are present:
MyISAM
Heap
Merge
INNO DB
ISAM
How to display top 50 rows?
SELECT * FROM
LIMIT 0,50;
how many column add in mysql table
MySQL supports up to 4096 columns per table.
how to store session in database
session_set_save_handler()
PHP provides a function that lets you override the default session mechanism by specifying the names of your own functions for taking care of the distinct tasks. I have organized this article according to these functions that you must write. For each function, I show you an example (using MySQL) and provide an explanation.
The function is called session_set_save_handler(), and it takes six arguments, each of which is the name of a function that you write. These functions are responsible for the following tasks:
Opening the session data store
Closing the session data store
Reading session data
Writing session data
Destroying all session data
Cleaning out old session data
<?php session_set_save_handler('_open', '_close', '_read', '_write', '_destroy', '_clean'); ?>
What are the objects can be created using CREATE statement?
Following objects are created using CREATE statement:
DATABASE
EVENT
FUNCTION
INDEX
PROCEDURE
TABLE
TABLE
TRIGGER
USER
VIEW
How many TRIGGERS are allowed in MySql table?
SIX triggers are allowed in MySql table. They are as follows:
BEFORE INSERT
AFTER INSERT
BEFORE UPDATE
AFTER UPDATE
BEFORE DELETE and
AFTER DELETE
In which language MySQL is written?
MySQL is written in C and C++
What is heap table?
Tables that are present in memory is known as HEAP tables. When you create a heap table in MySQL, you should need to specify the TYPE as HEAP. These tables are commonly known as memory tables. They are used for high speed storage on temporary basis. They do not allow BLOB or TEXT fields.
What is a trigger in MySQL?
A trigger is a set of codes that executes in response to some events.
What is the difference between heap table and temporary table?
Heap tables:
Heap tables are found in memory. They are used for high speed storage on temporary basis. They do not allow BLOB or TEXT fields.
Heap tables do not support AUTO_INCREMENT.
Indexes should be NOT NULL.
Temporary tables:
The temporary tables are used to keep the temporary data. Sometimes it is very useful in cases to keep temporary data. Temporary table is deleted after current client session terminates.
Main differences:
The heap tables are shared among clients while temporary tables are not shared.
Heap tables are just another storage engine, while for temporary tables you need a special privilege (create temporary table).
What is the difference between MySQL_connect and MySQL_pconnect?
Mysql_connect:
It opens a new connection to the database.
Every time you need to open and close database connection, depending on the request.
Opens page every time when it loaded.
Mysql_pconnect:
In Mysql_pconnect, "p" stands for persistent connection so it opens the persistent connection.
the database connection can not be closed.
it is more useful if your site has more traffic because there is no need to open and close connection frequently and every time when page is loaded.
How to display Nth highest salary from a table in a MySQL query?
To find Nth highest salary is:
select distinct(salary) from employee order by salary desc limit n-1,1
if you want to find 3rd largest salary:
select distinct(salary) from employee order by salary desc limit 2,1
What are the column comparison operators
The =, <>,<=,>=,, AND, OR, or LIKE operator may be used in column comparison to the left of the from in select statement.
How do you get no of row affected by query?
Select count(user_id) from users;
What are the heap table in mysql.
HEAP tables are in-memory . They are usually used for high-speed temporary storage.
NO Text or BLOB fields are allowed within HEAP tables.
you can only use the comparison operators = and < = >
HEAP tables do not support AUTO_INCREMENT.
Indexes must be NOT NULL.
How do you return the hundread book starting from 25th?
Select book_title from books limit 25, 100;
How would you select all the users, whose phone number is null?
Select user_name from users where ISNULL(mobileno);
What are ENUMs used for in MySQL?
You can limit the possible values that go into the table.
Create table months(month ENUM ‘january’,’February’, ‘march’);
Insert months values (‘april’).
What is the difference between char_length and length
The firstis, naturally , the characgter count.
The second is byte count.
How to get the current version of mysql?
Select version();
What is the difference between char and varchar
The char and varchar types are similar. But diff in the way they are stored and retrived.
The length of char column is fixed to the legth that you declare when you create the table.
The length can be any value between 1 and 255.
When char values are stored, they are right-padded with spaces to the specified length.
When char values are retrived, trailing spaces are removed.
How do you get current user in mysql
Select user();
How would you change a table to innoDB ?
Alter table name_file ENGINE innodb;
How do you cancatenate string in mysql ?
CONCAT(string1, string2, string3);
How do you display the list of database in mysql ?
Show databases;
How do you display the structure of the table ?
Describe table_name;
How do you find out which auto increment was assigned on the last insert ?
Select last_insert_id() will return the last value assigned by the auto_increment funtion.
NOTE :- you don’t have to specify the table name.
How do you control the max size of a HEAP table?
Maximum size of Heap table can be controlled using MySQL config variable called max_heap_table_size.
What is BLOB?
BLOB stands for binary large object.- It that can hold a variable amount of data.There are four types of BLOB based on the maximum length of values they can hold:- TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
What is TEXT?
TEXT is case-insensitive BLOB. The four types of TEXT are:- TINYTEXT- TEXT- MEDIUMTEXT- LONGTEXT
What is the difference between BLOB and TEXT?
- In BLOB sorting and comparison is performed in case-sensitive for BLOB values.
- In TEXT types sorting and comparison is performed case-insensitive.
What is difference between mysql_connect and mysql_pconnect?
Mysql_connect() opens a new connection to the database while mysql_pconnect() opens a persistent connection to the database. This means that each time the page is loaded mysql_pconnect() does not open the database. Mysql_close() cannot be used to close the persistent connection. Though it can be used to close mysql_connect().
How many columns we can update in single mysql query?
we can update 64 columns in single mysql query.
What is maximum length of column name, table name and database name?
column name can be upto 64 chars, table name can be upto 64 and database name can be upto 64 chars.
How do you get the number of rows?
SELECT COUNT (user_id) FROM users
would only return the number of user_id’s.
How would you select all the users, whose phone number is null?
SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
How would you write a query to select all teams that won either 2, 4, 6 or 8 games?
SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
How can you see all indexes defined for a table?
SHOW INDEX FROM questions
How would you delete a column?
ALTER TABLE answers DROP answer_user_id.
How would you change a table to InnoDB?
ALTER TABLE questions ENGINE innodb;
How do you get a portion of a string?
SELECT SUBSTR(name, 1, 10) from questions;
How do you convert a string to UTF-8?
SELECT (question USING utf8);
What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.
How to get the second highest salary of an employee from a employee table?
You can do this in two ways1) select salary from employee order by salary desc limit 1,1
2) select max(salary) from employee where max(salary)<(select max(salary) from employee)
How do you get the month from a timestamp?
SELECT MONTH(timestamp) from questions;
What are the techniques for query optimization?
Following are the some techniques of query optimization1) Use Indexes2) User limit (Don't pull extra records)3) Use only required fields (Don't pull extra fields which you are not going to use)
How can we get the number of rows affected by query?
SELECT COUNT (user_id) FROM users;
How to display top slary of 5 employeees?
SELECT * FROM users order by salary desc limit 0,5
How to get affected row
mysql_affected_rows
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
What is difference between DBMS and RDBMS. +
RDBMS (relational database management system) applications store data in a tabular form.
. DBMS store data as files .However there are is tables in DBMS also, but there is no relation between the tables as in RDBMS.
.In DBMS, data is generally stored in either a hierarchical form or a navigational form.
.In RDBMS tables have an identifier called primary key and Data values will be stored in the form of tables. The relationships between these data values will be stored in the form of a table as well. Every value stored in the relational database is accessible.
.RDBMS solution is required by large sets of data whereas small sets of data can be managed by DBMS.
What is difference between ORDER BY and GROUP BY in SQL +
ORDER BY used to sort the result in ascending or descending order. By default records are sort in ascending
Eg- SELECT column1, column2, …FROM tablename ORDER BY column1… ASC|DESC;
GROUP BY used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Eg- SELECT columnname FROM tablename WHERE condition GROUP BY columnname
How to find highest salary of the employee? +
SELECT MAX(SALARY) FROM EMPLOYEE
How to find second maximum salary? +
SELECT max(salary) FROM tblname WHERE salary < ( SELECT max(salary) FROM tblname )
get the employee with the maximum salary from department 30 +
SELECT *
FROM employees
WHERE department_id=7
AND salary = (SELECT MAX(salary)
FROM employees
WHERE department_id=7);
Get top 2 employee salary of the employee +
SELECT DISTINCT TOP 2 SALARY
FROM EMPLOYEE
ORDER BY SALARY DESC
How to find the third largest salary? +
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee)
);
If multiple employee have same salary. +
Suppose you have to find 4th highest salary
SELECT * FROM employee
WHERE salary= (SELECT DISTINCT(salary)
FROM employee ORDER BY salary LIMIT 3,1);
second largest salary. +
select *from employee
group by salary
order by salary desc limit 1,1;
What is difference between TRUNCATE and DELETE in mysql? +
1: DELETE is a DML(data manipulation lnguage) command whereas truncate is a DDL(data definition language) command.
2 : Truncate is much faster than Delete.
3 : We can not roll back in truncate but in delete we can rollback.
4 : We can not use where clause in truncate but in delete we can use conditions using where clausevv
What is difference between PRIMARY key and UNIQUE Key in sql? +
1: UNIQUE key can be a NULL value but PRIMARY key can not take NULL values.
2:A table can have multiple UNIQUE key but can only one PRIMARY key.
How to concatenate two fields in MySql
In MySQL CONCAT function is used to concatenate two strings to form a single string
Synatx : SELECT CONCAT(column1,column2) FROM tblname.
Ex : SELECT CONCAT(first_name,last_name) FROM employee
How to get current date in MySql +
SELECT CURRENT_DATE();
What is difference between MyISAM and InnoDB storage engines in mysql +
1 : InnoDB provides us row level locking while MyISAM provides us table level locking.
2 : InnoDB offers foreign key constraints wheres in MyISAM does not have foreign key constraints.
3 : InnoDB does not have full text search wheres MyISAM provides us full text search.
What type of storage engine mysql support? +
Below are some storage engines names that a mysql support.
1 : MyISAM.
2 :InnoDB
3 :Memory
4 :CSV
5 :Merge etc.
How to find unique records in MYSQL +
SELECT DISTINCT columnname FROM tablename;
how to fetch records sorted in an ascending (asc) or descending (desc) +
SELECT col1,col2 FROM tablename ORDER BY col2 DESC;
ELECT col1,col2 FROM tablename ORDER BY col2 ASC;
How to get total number of rows +
SELECT COUNT(*) FROM tablename;
How to add a column from a table +
alter table [table name] add column [new column name] varchar (20);
How do you return the a hundred items starting from 10th position +
SELECT item_name FROM items LIMIT 10, 100.
What is the difference between primary key and candidate key +
Every row of a table is identified uniquely by primary key. There is only one primary key for a table.
Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.
What is the different between NOW() and CURRENT_DATE() +
NOW () is used to show current year,month,date, hours,minutes and seconds.
CURRENT_DATE() shows current year,month and date only.
What is command to check table is exist +
CHECK TABLE table_name;
Write an SQL query to find names of employee start with ‘A’ +
SELECT * FROM Employees WHERE EmpName like ‘A%’ ;
What is heap table in MySQL +
Tables that are present in memory is known as HEAP tables. When you create a heap table in MySQL,you should need to specify the TYPE as HEAP. These tables are commonly known as memory tables. They are used for high speed storage on temporary basis. They don’t allow BLOB or TEXT fields.
1.How to get a employee record with max salary ? +
SELECT * FROM `tblemployes` where empSalary=(SELECT max(empSalary) from tblemployes);
How to get max salary in tblemployes ? +
SELECT max(empSalary) from tblemployes;
How to get 2nd highest salary in tblemployes ? +
SELECT max(empSalary)
from tblemployes
where empSalary not in (SELECT max(empSalary) from tblemployes)
How to get emp name, highest salary and department ? +
SELECT empName,empDept,empSalary
from tblemployes
where empSalary in (SELECT max(empSalary) from tblemployes)
How to get highest salary of each department ? +
SELECT empDept,empSalary
from tblemployes
where empSalary in (SELECT max(empSalary) from tblemployes group by empDept)
How to get number of employee in each department ? +
SELECT empDept,COUNT(empName)
from tblemployes group by empDept
How to get distinct id from two table. suppose table one contain id:-1,2,3,4....10. and table two contain id:- 1,2,3,4,........20. write query to show
id from table2, 11,12,13....20.+
SELECT `id` FROM `users` WHERE `id` NOT IN(SELECT DISTINCT `id` FROM `user_info`)
SELECT DISTINCT users.id FROM users LEFT JOIN user_info USING (id) WHERE user_info.id IS NULL
how to find record between two date in mysql. +
SELECT * FROM user_info WHERE created_at BETWEEN CAST('2019-01-01' AS DATE) AND CAST('2019-08-20' AS DATE)
+
SELECT *
FROM order_details
WHERE order_date >= CAST('2019-01-01' AS DATE)
AND order_date <= CAST('2019-08-20' AS DATE);
Using NOT Operator
BETWEEN condition can also be combined with the NOT operator +
SELECT *
FROM suppliers
WHERE supplier_id NOT BETWEEN 2000 AND 2999;
return all rows from the suppliers table where the supplier_id was NOT between 2000 and 2999 +
SELECT *
FROM suppliers
WHERE supplier_id < 2000
OR supplier_id > 2999;
+
+
+
+
+