Showing posts with label Basic SQL. Show all posts
Showing posts with label Basic SQL. Show all posts

SQL Query Example and Sample SQL Commands Queries

MYSQL Query Example


CHAR_LENGTH() Example


CHAR_LENGTH() function is used to count the character in the given String.

  SELECT question, explainans, `view`, CHAR_LENGTH(explainans) AS lengt 
FROM `question` WHERE explainans IS NOT NULL AND CHAR_LENGTH(explainans) > 200 
ORDER BY `view` DESC



GROUP BY() Example

 SELECT created_at, COUNT(*) FROM `application_for_otherexam` WHERE exam_id = '8' 
GROUP BY DATE(created_at)

 SELECT created_at, COUNT(*) AS Total FROM `application_for_otherexam` 
WHERE exam_id = '8'  AND form_status='55' GROUP BY DATE(created_at)



General Sample MY SQL Query Example

 SELECT COUNT(*) AS Total FROM `application` WHERE formstatus IN('4', '44', '55') 
AND examid='8'

 SELECT school_name, code FROM `school_master` WHERE code IN('22','31','31')

 SELECT CONCAT(FIRST_NAME,' ',LAST_NAME) AS WORKER_NAME FROM WORKER WHERE 
CONCAT(FIRST_NAME,' ',LAST_NAME) LIKE '%hal'

 SELECT YEAR(dob), COUNT(*) AS TOTAL FROM STUDENT_DETAILS GROUP BY YEAR(DOB) 
HAVING TOTAL>10 ORDER BY YEAR(DOB) ASC

 SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME), SALARY FROM WORKER WHERE SALARY
BETWEEN 50000 AND 100000 

 SELECT APPCOMMADDR1, LENGTH(APPCOMMADDR1) AS T1, APPCOMMADDR2, 
LENGTH(APPCOMMADDR2) AS T2, APPCOMMADDR3, LENGTH(APPCOMMADDR3) AS T3 
FROM `Data_Dump_Dept_exam_dec2019_20191203` HAVING T1>50 AND T2>50 AND T3>50


MYSQL Sub Queries Example

 SELECT udiscode FROM schoolmaster WHERE code IN ( SELECT SCHL FROM `udise_mapping`
GROUP BY SCHL HAVING COUNT(*)>1)



CONCAT(), UPPER(), LOWER() Function Example

 SELECT UPPER(FIRST_NAME) AS FNAME, UPPER(LAST_NAME) AS LNAME, 
CONCAT(UPPER(FIRST_NAME),' ',UPPER(LAST_NAME))AS FULLNAME FROM WORKER 
ORDER BY FULLNAME ASC

 SELECT CONCAT(FIRST_NAME,' ',LAST_NAME) AS WORKER_NAME FROM WORKER WHERE 
CONCAT(FIRST_NAME,' ',LAST_NAME) LIKE '%hal'



SQL DATE(), YEAR(), MONTH() Function Example

 SELECT CURDATE() 

 SELECT YEAR(CURDATE())

 SELECT MONTH(CURDATE())

 SELECT DAY(CURDATE())

 SELECT NOW()

 SELECT YEAR(NOW())

 SELECT MONTH(NOW())

 SELECT HOUR(NOW())

 SELECT MINUTE(NOW())

 SELECT SECOND(NOW())
 SELECT * FROM WORKER WHERE MONTH(JOINING_DATE) = 6 ORDER BY SALARY DESC LIMIT 2

 SELECT  MONTHNAME(STR_TO_DATE(MONTH(dob),'%m')) AS mname, COUNT(*) AS totalno 
FROM `student_details` WHERE MONTH(dob) =1 GROUP BY MONTHNAME(STR_TO_DATE(MONTH(dob),'%m'))



Example Using Case in MYSQL Query

 SELECT COUNT(
       CASE
           WHEN roll_no IS NULL
           THEN 1
           ELSE NULL
       END
   ) AS 'not_complete',
   COUNT(
       CASE
           WHEN  roll_no IS NOT NULL
           THEN 1
           ELSE NULL
       END
   ) AS 'completed'
    FROM `application`
WHERE examid =7

 SELECT school_id, COUNT(
       CASE
           WHEN formstatus = '4'
           THEN 1
           ELSE NULL
       END
   ) AS 'Initiated',
   COUNT(
       CASE
           WHEN  formstatus = '45'
           THEN 1
           ELSE NULL
       END
   ) AS 'Payment Pending',
   COUNT(
       CASE
           WHEN  form_status = '55'
           THEN 1
           ELSE NULL
       END
   ) AS 'Payment Done'
    FROM `application` 
WHERE examid =7 GROUP BY school_id

 SELECT COUNT(
CASE 
  WHEN gender = 'MALE'
  THEN 1
  ELSE NULL
  END 
  ) AS MALECOUNT, 
COUNT(
CASE 
  WHEN gender = 'FEMALE'
  THEN 1
  ELSE NULL
  END 
  ) AS FEMALECOUNT, COUNT(*) AS Total 
FROM `application` WHERE exam_id='8' AND form_status IN('55')



Using MYSQL IF statement with Example

 SELECT b.centre_id,COUNT(IF(MED='TAMIL' OR  MED='ENGLISH',1,NULL)) AS TAMENG,
COUNT(IF(MED='KANNADA',1,NULL)) AS KANNADA,
COUNT(IF(MED='HINDI',1,NULL)) AS HINDI,
COUNT(IF(MED='URDU',1,NULL)) AS URDU,
COUNT(IF(MED='ARABIC',1,NULL)) AS ARABIC,
COUNT(IF(MED='PERSIAN',1,NULL)) AS PERSIAN,
COUNT(IF(MED='LATIN',1,NULL)) AS LATIN,
COUNT(IF(MED='ENGLISH',1,NULL)) AS ENGLISH FROM `dummynoexam`a
JOIN `examrollnumber` b ON a.student_id=b.student_id AND a.class_id=b.class_id 
AND a.sess_id=b.sess_id
JOIN  centremasterexam cm FORCE INDEX(cent_class_sess) ON   b.centre_id=cm.CENT 
AND b.class_id=cm.CLASS_ID AND b.sess_id=cm.SESS_ID
GROUP BY SUB,b.centre_id

 SELECT COUNT(IF(statusflag = 1, 1, NULL)) AS STATUS1, COUNT(IF(statusflag=0, 1, NULL)) 
AS STATUS0, COUNT(IF(statusflag IS NULL,1, NULL)) AS STATUSNULL FROM `student`



MYSQL LPAD AND MID FUNCTION() USAGE and Example

SELECT `code`, MID(district_name,1,4) AS prefix, CONCAT(prefix,LPAD(`code`,4,0)) 
FROM `educational_district`


Set the Variable in MYSQL

SET @a:=1;  // Run this first and then run the query

SELECT e.code, s.dge_code, centre_id, rollno, student_group_id, subject_id, medium_id, @a:=@a+1 AS ID   FROM `student_pappermapping` a JOIN `student_exam_details` b ON a.student_exam_details_id =b.id
JOIN `student_details` c ON b.student_id= c.id 
JOIN `subject_list` d ON d.SUBJECT = a.subject_id AND b.class_id=d.CLASS_ID
JOIN school_master s ON c.school_id=s.id
JOIN `educational_district` e ON s.district_id=e.id
JOIN  `exam_rollnumber` r ON r.student_id=c.id AND r.class_id = b.class_id AND r.sess_id=b.sess_id
WHERE c.school_id =1345 AND b.class_id =3 AND b.sess_id= 1 AND (d.TTAG='P' OR LNKSUB <> '')  
ORDER BY e.code, dge_code, student_group_id, subject_id, medium_id



SELECT sr.student_id, doe.ROLLNO, doe.NAME, COUNT(*), (GROUP_CONCAT(sr.subject_id SEPARATOR ', ')) AS applied_subjects
FROM `student_revaluation` sr JOIN `dummy_no_exam` doe ON doe.student_id = sr.student_id AND doe.SUB = sr.subject_id GROUP BY sr.student_id





MySql Date Function and Query Example


MySql Date() Function List for Your Reference with Query Example. Consider Below table for Executing all the MySql Date Function.

Consider Below table Named with  Personal_Detail

FULLNAME
DOB
CREATED_AT
MUNISHA D
31-10-1996
14-11-2019 09:43
ANANTHA KUMAR C
20-08-2008
14-11-2019 10:12
THIRUMALAIKUMAR 
28-06-2003
14-11-2019 09:53
DHANALAXSHMI S
10-06-2004
14-11-2019 10:11
AGNES LIDIA A
21-04-2003
14-11-2019 00:14
MOHANASRI G
28-05-2004
14-11-2019 10:12
PRIYANKA P
12-05-2001
14-11-2019 09:44
RANJITHKUMAR R
02-07-2004
14-11-2019 10:11
SABESH S
03-06-2005
14-11-2019 09:54
AMSAVALLI E
07-06-2004
14-11-2019 10:02

We will Write query to extract the data using MySql Date() function. Kindly go through the basic and view the query in the last for enhancing your SQL Skills.

MySql Date() Function with Example



   CURDATE()  MySql Function : Once the below query will run it will O/P The current Date.

  SELECT CURDATE()    

   O/P : 2020-04-29  



   CURTIME()  MySql Function :  Below Query will give you the Current time detail whatever time it is. Time will be in "HH-MM-SS" (string Format)

    SELECT CURDATE()    

    O/P : 12.52.09 


MySql Current TimeStamp Function 



   CURRENT_TIMESTAMP()  MySql Function :  CURRENT_TIMESTAMP will return the Date with time

    SELECT CURRENT_TIMESTAMP()    

    O/P : 2020-04-29 19:44:07



   DATE()  MySql Function :  DATE() function will be used to compare the date or to extract the date.

      SELECT  DATE("2020-04-29  06:34:21")

      O/P : 2020-04-29 



   MONTH()  MySql Function :  MONTH() function will be used to extract the month from the given Date.

      SELECT  MONTH("2020-04-29  06:34:21")

      O/P : 4 



   DAY()  MySql Function :  DAY() function will be used to extract the DAY from the given Date.

      SELECT  DAY("2020-04-29  06:34:21")

      O/P : 29 



   DATEDIFF()  MySql Function :  DAYDIFF() function will compare the two date and return the number of day. Syntax : DATEDIFF(dateSel1, dateSel2)

      ⇒ SELECT  DATEDIFF("2020-10-29", "2020-04-29")

      O/P : 183

      ⇒ SELECT DATEDIFF"2021-10-29, CURDATE()

      O/P : 548

       ⇒ SELECT DATEDIFF"2021-07-29  09:34:21, CURRENT_TIMESTAMP() )

      O/P : 456



   DATE_ADD()  MySql Function :  DATE_ADD() function will add DAY, TIME, MONTH in the given date. Syntax : DATE_ADD(dateSel1, INTERVAL value  UnitAdd). UnitAdd can be DAY, WEEK, MONTH, YEAR, SECOND, MINUTE, HOUR etc..

      ⇒ SELECT  DATE_ADD("2020-10-29", INTERVAL  10  DAY )

      O/P : 2020-11-08

      ⇒ SELECT  DATE_ADD("2020-10-29", INTERVAL  10  MONTH )

      O/P : 2021-08-29

      ⇒ SELECT  DATE_ADD( CURRENT_TIMESTAMP() , INTERVAL  10  MONTH )

      O/P : 2021-02-28 20:08:34



   DATE_SUB()  MySql Function :  DATE_SUB() function will substract DAY, TIME, MONTH in the given date. Syntax : DATE_SUB(dateSel1, INTERVAL value  UnitSub). UnitSub can be DAY, WEEK, MONTH, YEAR, SECOND, MINUTE, HOUR etc..

      ⇒ SELECT  DATE_SUB("2020-10-29", INTERVAL  10  DAY )

      O/P : 2020-10-19

      ⇒ SELECT  DATE_SUB("2020-10-29", INTERVAL  10  MONTH )

      O/P : 2019-12-29

      ⇒ SELECT  DATE_SUB( CURRENT_TIMESTAMP() , INTERVAL  10  MONTH )

      O/P : 2019-06-29 20:12:43



   DATE_FORMAT()  MySql Function :  Know Basic Prefix for DATE_FORMAT()
  • "%D" : It will return the day in numeric form with suffix like 1st, 2nd, 3rd, etc.  
  • "%d"  : It will return the numeric value without suffix like 1, 2, 3, 4,..
  • "%M" : It will return the month name fully.
  • "%m" : It will return the month in numeric form.
  • "%Y" : It will return the full year in four digit 2020, 2019, 2018 etc..
  • "%y"  : It will return the year in two digit 20, 19, 18, 17 etc..
     
      ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%D" )
      O/P : 29th

      ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%d" )
      O/P : 29

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%M" )
      O/P : April

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%m" )
      O/P : 04

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%Y" )
      O/P : 2020

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%y" )
      O/P : 20

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%Y  %M" )
      O/P : 2020 April

       ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%Y  %M %D" )
      O/P : 2020 April 29th

      ⇒ SELECT  DATE_FORMAT( CURRENT_TIMESTAMP() ,  "%Y /%m/%d" )
      O/P : 2020/04/29



   NOW()  MySql Function :  It will return the current time and stamp in the format of "YYYY-MM-DD HH.MM.SS". NOW() Function and CURRENT_TIMESTAMP() will return the same value. 

  ⇒ SELECT NOW( )

      O/P : 2020-04-29 22:09:57

60 Top SQL Interview Question for Experience and Fresher Professional

mySql Interview Question

SQL Interview Question for Experience and Fresher


1) Define Key and It's Type?

  • Primary Key is table-column which consist unique value and cannot be NULL. A table can have only one primary key in it. Primary Key is in sorted Order by Default.
  • Unique Key is a table-column which consist unique value and it can be NULL. A Database Table can have many Unique Column in it.

  • Foreign Key is a table-column or group of Table-column which set the relation between two table. Foreign Key of one table have the reference to the Primary key of another Table.

  • Alternate Key is table Column or Group of column which identify each row in a table uniquely and not be NULL, But it is not a primary key. Alternate Key is Unique Identifier in table. In 
  • Super Key is set key of one or more table-column which identify the table row uniquely. Super Key set in below table is {REGNO}, {ROLLNO}, {REGNO,ROLLNO}     
ID
REGNO
ROLLNO
FULLNAME
DOB
1
2020001435
10011
M Kumar
07-04-2003
2
2020001437
10012
MOHAMMED ISHAQ  H
14-06-2002
3
2020001478
10013
ANBUSELVAM S
18-06-2004
4
2020001487
10014
MARTINPRIYADOSS J
08-03-2004


  • Candidate Key is a column or group of column which consist unique value and not be Null. We select primary key from the group of candidate Key. We can say candidate Key is minimal set of Super Key with no duplicate record. {REGNO}, {ROLLNO}
Points To Remember :
  1. Primary Key can act as a Unique Key, but Unique Key can't be Primary key because it Can contain Null Value. 
  2. Candidate key is Minimal set of Super Key with no redundant record.


2)  How to use pattern matching operator in SQL Query?

LIKE is SQL Pattern matching operator which is used with Where Clause. '%' and '_' is used with LIKE.

  • '%',  Percent is used for 0, 1 or multiple Characters.
  • '_' , Underscore is used for single character.  
Consider Student_Table and Queris using Like Operator

FullName
DOB
M KUMAR
07-04-2003
MOHAMMED ISHAQ
14-06-2002
ANBUSELVAM S
18-06-2004
MORTINPRIYADOSS JAMES
08-03-2004
JAGAN J
10-04-2003
NAVEENKUMAR
02-06-2004
HARIKRISHNAN R
15-11-2003
VIJAY K
14-11-2002
SUTHAKAR
23-03-2004
KATHIRESAN P
15-11-2007

For Example : 

  • SELECT  *  FROM Student_Table  WHERE  FullName  LIKE  "MO%"  (MO% it means FullName start with MO) 

FullName
DOB
M KUMAR
07-04-2003
MOHAMMED ISHAQ  H
14-06-2002

  • SELECT * FROM Student_Table  WHERE  FullName  LIKE  "%MAR"  (%MAR it means FullName ends with MAR)
FullName
DOB
M Kumar
07-04-2003
NAVEENKUMAR
02-06-2004
  • SELECT * FROM Student_Table  WHERE  FullName  LIKE  "%PRIYA%"  (%PRIYA% it means FullName which contain PRIYA)
FullName
DOB
MORTINPRIYADOSS JAMES
08-03-2004


3) What is Clause in Sql?

Clause in SQL is condition which limit the fetched record by applying condition. Its is like Filter some record from set of table record.

There are Five SQL Clause.
  • ORDER BY Clause
  • TOP Clause
  • WHERE Clause
  • GROUP BY Clause
  • HAVING Clause 
Consider Student_Table for writing SQL Clause Example:

FullName
DOB
MARKS
M KUMAR
07-04-2003
60
MOHAMMED ISHAQ
14-06-2002
63
ANBUSELVAM S
18-06-2004
75
MORTINPRIYADOSS JAMES
08-03-2004
56
JAGAN J
10-04-2003
73
NAVEENKUMAR
02-06-2004
86
HARIKRISHNAN R
15-11-2003
45
VIJAY K
14-11-2002
32
SUTHAKAR
23-03-2004
94
KATHIRESAN P
15-11-2007
87

WHERE Clause Example:
SELECT * FROM Student_Table  WHERE  YEAR(DOB) = 2007
SELECT * FROM Student_Table  WHERE  MARKS BETWEEN 73 AND 90
ORDER BY Clause Example
SELECT * FROM Student_Table  ORDER BY MARKS DESC
SELECT * FROM Student_Table  WHERE  MARKS > 70 ORDER BY MARKS DESC

GROUP BY Clause Example
SELECT MARKS, COUNT(*) FROM Student_Table  GROUP BY MARKS
SELECT * FROM Student_Table WHERE YEAR('DOB') >2003  GROUP BY MARKS 

HAVING Clause Example
SELECT MARKS, COUNT(*) AS TOTALCOUNT FROM Student_Table  
GROUP BY MARKS HAVING TOTALCOUNT > 5

4) What is the Main Difference between WHERE Clause and HAVING Clause ?


  • WHERE Clause and HAVING Clause is especially for filtering the set of record from the table based on the condition. 
  • WHERE Clause cannot be used with SQL Aggregate Function Like COUNT(), SUM(), AVG() where HAVING Clause can be used.
  • HAVING Clause filter the set of record from the group row not on Individual row, WHERE Clause filter the record Set from the Column row.
The Main difference WHERE Clause and HAVING Clause you can understand using with GROUP BY in the same query.

Query Example: 

SELECT * FROM Student_Table WHERE MARKS < 80 GROUP BY MARKS HAVING TOTALCOUNT > 1
In the above query first Student_Table record will be filter using WHERE Clause, then it will be grouped and again it will be filtered on the group row using HAVING.



5) What is Constraint?

Constraint are the rules and limitation we apply while creating and altering table column in the database which restrict the unwanted data.

Some Constraint we apply while creating the Table is below for your reference.
  • NOT NULL this constraint ensure that NULL value can't be inserted.
  • DEFAULT will automatically assign the value if no value has been assigned.
  • UNIQUE this will ensure that all the entered value in the column will be unique.
  • INDEX it created the index based on the column for faster retrieval of Data from the database.
  • PRIMARY KEY Ensure that each record in the table must be unique and not null.   



6) What is View ?

View is Virtual Table which consist of rows and column like real table. We create view by selecting column field from one or more Database table.

It donot store any data of its own but it just display the data of other table.

View help us in data Security. Using View we can allow only limited access of data from the various table.

Below is the example for creating view :

CREATE VIEW `StudentInfo` AS SELECT `st.firstName`,`st.mobileNo`, 
`st.gender`,`sa.city`,`sa.pincode` FROM studentTable as st 
JOIN studentAddress as sa on st.id = sa.student_id;



7) Difference Between DELETE and TRUNCATE commands ?

Delete Command will delete the rows from the Database Table based on certain criteria and conditional Parameter Set. Delete statement allow us to perform Commit and Rollback.

Truncate Command will truncate all rows from the database table. It Cannot be rolled Back.



8) What is ACID property in a Database?

DB ACID Property


ACID stands for Atomicity, Consistency, Isolation, Durability.

Atomicity Ensure that either all the transaction must be succeeds or none in the database, It must not be in partial State. Atomicity ensures that partial Transaction must not happen in Database it must complete or  none of it.

Consistency Ensure that database transaction must happen in isolation. Here Isolation means concurrent database transaction process must not run.

Isolation Database Property ensure that once one transaction get complete then only other Database Transaction must start. Isolation means at a time only one Transaction process must execute. No Concurrent transaction process must run.

Durability Property ensures that once Transaction Process is completed successfully then in any case (Like System failure, power cut etc. ) the database must not get affect. Durability of Database must be maintain in all the condition. 

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post