Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

introduction to databases

 what is daata


data is -> any sort of information which is stored on paper or in digigtal 

contacts

emails

messages in wahtasapp

multimedia

location data in maps

twets / posts on oscial media


photots to be uploaded in social media  is called data

if we clcks on ads, it will catch ip address, tahta will stored as data


in this mannaer it will generate more amount data






who is using data

companies cannot required raw data, they require 

to build attractive econonmy -> they are usign reward/coupon model
which company will give good revenwu-> to take a good decisiaon thye need data

data is the mnain thing to get revenue

data is the heart of the applciations

applcition developers
vital healt care
technologiecal inforatmion 
entertainment 

practo
spotify
wikipedia


to bring services to finger tips of the people ( we need data)

to help digitize nations (gpay , phone pe)

to build like above applicaitons we need data

ai/ml engineers use data to build integliigent softwares



perosnal assigsts like goolg voiece
virtual health assiants like med waht
chatgpt

they have all questions ans anseers , using data , if i questioin anything it wil answer 

thats the greatness of data
\
autonomosu vehicles like 
uber , tesla

autonomuse vehcils
they have to train on lot of dat ( who is at frotn what action have to take)



data scientis

they wikl collect data to geenrate deeper insights helping organisatons make data-driven decisions



it enhance custome experience and resource optmisaiton

to perform any operation on the data, it should be stred in an organisaed way

data base -> it is a collection of  data



database management system -> used to easily storea nd access data from the database in  a secure way





php my admin, sql work bench

using dbms to store and maintian their data

data is any type, like music, messsage, media, video,  ---



sql order of execution

 We all know SQL, but most of us do not understand the internals of it.


Let me take an example to explain this better. Select p.plan_name, count(plan_id) as total_count From plans p Join subscriptions s on s.plan_id=p.plan_id Where p.plan_name !=’premium’ Group by p.plan_name Having total_count > 100 Order by p.plan_name Limit 10; Step 01: Get the table data required to run the sql query Operations: FROM, JOIN (From plans p, Join subscriptions s) Step 02: Filter the data rows Operations: WHERE (where p.plan_name=’premium’) Step 03: Group the data Operations: GROUP (group by p.plan_name) Step 04: Filter the grouped data Operations: HAVING (having total_count > 100) Step 05: Select the data columns Operations: SELECT (select p.plan_name, count(p.plan_id) Step 06: Order the data Operations: ORDER BY (order by p.plan_name) Step 07: Limit the data rows Operations: LIMIT (limit 100) Knowing the Internals really help. where does distinct keyword fits in the above ordering? Do mention in comments.
#bigdata #dataengineering #sql

task by hasone testdome

==


vuejs task
write the reoraderable list component . the component should recieve an array of elements as items prop and should displa the elements as list items in an unorderseed list
when the user click on a list item it should be sent to the first positionin the unordered list
for example if the component has the item prop ["A","B","C"], the list should look like:

<!DOCTYPE html> <html> <head> <title>Reorderable List</title> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div id="app"> <reorderable-list :items="['A', 'B', 'C']"></reorderable-list> </div> <script> Vue.component('reorderable-list', { props: ['items'], data() { return { list: [...this.items] }; }, methods: { moveToFirst(index) { const item = this.list.splice(index, 1)[0]; this.list.unshift(item); } }, template: ` <ul> <li v-for="(item, index) in list" :key="index" @click="moveToFirst(index)"> {{ item }} </li> </ul> ` }); new Vue({ el: '#app' }); </script> </body> </html>


== 

second task

convert a string of numbers to a sentnce .e ach number represents a aletter. numbers in  the string are seperated by  aspace. and words in the sentence are seperated by a plus characterf/

conversion table:

1 = A

2 =B

--

26 = Z


example numbe to letters (`20 15 19 20+4 15 13 5) should return 'test dome'


<?php function numberToLetters($string) { $conversionTable = [ 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z' ]; $words = explode('+', $string); // Split string into words separated by '+' $result = []; foreach ($words as $word) { $letters = explode(' ', $word); // Split each word into numbers separated by spaces $wordResult = ''; foreach ($letters as $number) { if (isset($conversionTable[$number])) { $wordResult .= $conversionTable[$number]; } } $result[] = $wordResult; } return strtolower(implode(' ', $result)); // Convert result to a sentence in lowercase } // Example usage echo numberToLetters('20 5 19 20+4 15 13 5'); // Outputs: test dome ?>


echo numberToLetters('20 5 19 10+4 15 13 5');

===============================

implement the get view count method .it should accept a json 

a string and sum all vie wcount fields inside the json will alwyas hav ethe same structure as int he example case 

for example calling get view count should return 88270796 for the following $jsonstring 

{

  "apiVersion": "2.1",

  "videos": [

    {

      "id": "253",

      "category": "music",

      "title": "Jingle Bells",

      "duration": 457,

      "viewCount": 88270796

    }

  ]

}

==

<?php function getViewCount(string $jsonString): int { $data = json_decode($jsonString, true); $totalViewCount = 0; if (isset($data['videos']) && is_array($data['videos'])) { foreach ($data['videos'] as $video) { if (isset($video['viewCount'])) { $totalViewCount += $video['viewCount']; } } } return $totalViewCount; } $jsonString = ' { "apiVersion": "2.1", "videos": [ { "id": "253", "category": "music", "title": "Jingle Bells", "duration": 457, "viewCount": 88270796 } ] } '; echo getViewCount($jsonString); ?>


===

writea a function that removes all items that are not integers from the array the function should modify the existing aarray,nmot create a nbew one.

for example, if the input array containes values [1,'a,'b',2], after processing, the array will contain only values [1,2]

<?php function filterNumbersFromArray(array &$arr): void { foreach ($arr as $key => $value) { if (!is_int($value)) { unset($arr[$key]); } } } $arr = [1, 'a', 'b', 2]; filterNumbersFromArray($arr); print_r(array_values($arr)); ?>

==============


an education magazine pulbishee rankings of strudnetns and theire colleges in a acompetitoion in building unmmaned aerial vehical dornes. students whoi participated in the competion in different yeres, their ranking in the competion, and their colleges are contained inthe following tables;

table colleges 

id integer primary key

name varchar(50) not null


table students 

id integer primary key 

name varchar(50) not null 

collegeid integer

foreighn key (collegeid) references colleges(id)


table rankings 

studentid integer 

ranking integer not null

year integer not null

foreign key (studentid) references students(id)


write a query that lists all collges that have atleast one student with a ranking between 1 and 3 ( both inclusive) for the year 2015. the query should return 

the college name,

the rank of their best rnaking studnet for 21015.;

the numer of students who had rankings between 1 and 3 ( both inclusive) for the year 2015

rank 1 is the best rank, rank 2 is the second best an dso on . more than one student can tie for a rank in a ayear


SELECT
c.name AS college_name,
MIN(r.ranking) AS best_rank_2015,
COUNT(*) AS num_students_rank_1_to_3
FROM
rankings r
JOIN
students s ON r.studentid = s.id
JOIN
colleges c ON s.collegeid = c.id
WHERE
r.year = 2015
AND r.ranking BETWEEN 1 AND 3
GROUP BY
c.name;


=



=


As part of a data processing pipeline, complete the implementation of the make_pipeline method:

  • The make_pipeline method should accept a variable number of functions, and it should return a new function that accepts one parameter $arg.
  • The returned function should call the first function in make_pipeline with the parameter $arg, and call the second function with the result of the first function.
  • The returned function should continue calling each function in make_pipeline in order, following the same pattern, and return the value from the last function.

For example, calling make_pipeline(function($x) { return $x * 3; }, function($x) { return $x + 1; }, function($x) { return $x / 2; }), and then calling the returned function with 3 should return 5.

<?php

function make_pipeline(...$funcs)
{
return function ($arg) use ($funcs) {
$result =$arg;
foreach ($funcs as $func){
$result = $func($result);
}
return $result;
};
}

$fun = make_pipeline(
function ($x) {
return $x * 3;
},
function ($x) {
return $x + 1;
},
function ($x) {
return $x / 2;
}
);
echo $fun(3); # should print 5

===

App usage data are kept in the following table:

TABLE sessions
  id INTEGER PRIMARY KEY,
  userId INTEGER NOT NULL,
  duration DECIMAL NOT NULL

Write a query that selects userId and average session duration for each user who has more than one session.


SELECT userid, AVG(duration) AS avg_duration
FROM sessions
GROUP BY userid
HAVING COUNT(id) > 1;

=

questions:

what is abstract and what is interface

why we use abstaract

what is difference

why do we interface

wht is static method


where can use static, where can we declare static

solid principles

design pattern 

whtis service container and service provider

array methods 

what type of array in php supports

session and cookie

what is http only cookie

what is break and continue 

how can we handle exceptions

what is finally in php

whatr is composer

what is composer.lock

how to update the pacakge 

how can we update teh specific pakage

life cycke method in vuejs

how to bind the data 

what is v-model

event emitters

what is props and data functions 

hwo can we declare a method in vuejs

what is pure function in javascript


set time out and set interval

how to stop the setinterval

hosting in javascript

waht is closure in javacript

sql

what are join in sql

what is self join

what is inner  join

what is group by

what is indexing mechanism

what is composite index

aany experience in version control system and what is the workf low








most frequently asked sql interview questions

 


























interview questions in sql

 what is ht ebasic tstructure osf a select statement in sql

how can you prevent sql injection attacks

can you write a sql query to find the top 5 cutomers based on their purchase history

list two common aggretgte functioions used ins qsl

differentiate between union and union all for combining datasets

what are subqueries and how canyou use them in sql statements

how to sort data in asecnding order and decending order using order by

how to group data and aply aggregate functions (count, sum, avg) using group by

how do you filter data based on specifi condtions using where clause

how do you join multiple tables in sql,explain different data types

what is the basic structure of a select statemen in sql


task by myverkoper.com

 <!-- SELECT Rank

FROM Persons
WHERE Rank < (SELECT MAX(Rank) FROM Persons)
ORDER BY Rank DESC -->

task:2
With out using limit in query, display 2nd highest rank person

is it right

wild card characters in sql

 Wildcard characters in SQL are special characters that allow you to perform pattern matching in string comparisons. These characters are often used in conjunction with the LIKE operator to filter rows based on specific patterns within text columns. The two main wildcard characters in SQL are the percent sign (%) and underscore (_).

  1. Percent Sign (%) Wildcard:

    • The percent sign (%) represents zero or more characters in a string.
    • Syntax: SELECT column_name FROM table_name WHERE column_name LIKE 'pattern%';
    • Example:
      sql
      SELECT * FROM employees WHERE employee_name LIKE 'J%';
      This query retrieves all employees whose names start with the letter 'J'.
  2. Underscore (_) Wildcard:

    • The underscore (_) represents a single character in a string.
    • Syntax: SELECT column_name FROM table_name WHERE column_name LIKE 'pattern_';
    • Example:
      sql
      SELECT * FROM products WHERE product_code LIKE 'AB_%';
      This query retrieves products with codes starting with 'AB' followed by any single character.

Combined Wildcards: You can also combine these wildcard characters to create more complex patterns:

  • LIKE 'pattern%' matches strings that start with 'pattern'.
  • LIKE '%pattern' matches strings that end with 'pattern'.
  • LIKE '%pattern%' matches strings that contain 'pattern' anywhere in the string.

Note:

  • The LIKE operator is case-insensitive by default in many SQL database systems, but this behavior can vary. You can use the COLLATE clause to specify case sensitivity if needed.
  • Wildcard characters can affect query performance, especially when used at the beginning of a pattern, as they can prevent efficient index usage. It's essential to use wildcards judiciously to avoid performance issues.

Do you need more examples or information about using wildcard characters in SQL queries?

self join in laravel

 

A self join in SQL is a type of join where a table is joined with itself. This is useful when you want to compare rows within the same table or create relationships between different rows in the same table. Self joins are typically performed using aliases to differentiate between the two instances of the same table. Here's an explanation and example of a self join:

SELECT t1.column_name, t2.column_name FROM table_name t1 INNER JOIN table_name t2 ON t1.common_column = t2.common_column;

In this syntax:

  • table_name is the name of the table you're performing the self join on.
  • t1 and t2 are aliases for the same table, used to differentiate between the two instances.
  • common_column is the column that both instances of the table share and use to establish the relationship.

Example: Consider a table named employees with columns employee_id, employee_name, and manager_id, where manager_id is a foreign key that references the employee_id of another employee who is the manager of the current employee. Here's how you might use a self join to get the names of employees and their respective managers:

sql
SELECT e.employee_name AS employee, m.employee_name AS manager FROM employees e INNER JOIN employees m ON e.manager_id = m.employee_id;

In this example:

  • e is an alias for the employees table (as the employee).
  • m is an alias for the employees table (as the manager).
  • We join employees with itself based on the condition e.manager_id = m.employee_id.
  • This query retrieves the names of employees and their respective managers by joining the employees table with itself.

Self joins are particularly useful in hierarchical structures like organizational charts or when dealing with relationships within the same entity, such as employee-manager relationships or parent-child relationships in a hierarchical data model.

Syntax:


SELECT t1.column_name, t2.column_name FROM table_name t1 INNER JOIN table_name t2 ON t1.common_column = t2.common_column;

Hey Folks, It’s Worse Than We Thought — Claude’s Privacy Mess Just Got Bigger

  What started as a leak of shared Claude chats has turned into something much bigger — and much worse. The same thing is now happening with...