Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In Java, a logical OR condition behaves such that if the first condition is `true` then it does not evaluate the second condition. For example: ``` int a = 10; if (a == 10 || a == 0) { // Logic } ``` Java does not evaluate the second test (`a == 0`) because the first condition (`a == 10`) is `true`. If we have ...
### PL/SQL In PL/SQL, Oracle OR is another example of *short circuit* evaluation. Oracle [PL/SQL Language Fundamentals](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/fundamentals.htm#LNPLS258) says (in part) > ### Short-Circuit Evaluation > > When evaluating a logical expression, PL/SQL uses **short-circuit e...
The database cost optimizer will consider many factors in structuring the execution of a query. Probably the most important will be the existence of indexes on the columns in question. It will decide the order based on the selectivity of the test and could perform them in different order at different times. Since SQL i...
How does Oracle perform OR condition validation?
[ "", "sql", "oracle", "logical-operators", "" ]
Trying to insert values into a temporary table using SQL Server 2008, getting: > Msg 116, Level 16, State 1, Procedure Test\_temp\_table, Line 274 > Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. With this query: ``` VALUES( (select a.*, b.[formal nam...
If you are not going to create the temp table first, use select into. ``` IF OBJECT_ID('TEMPDB.DBO.#TEMP') IS NOT NULL DROP TABLE #TEMP; BEGIN SELECT a.*, b.[formal name], c.*, d.* INTO #TEMP FROM selecthr20.employee.[career history] a, INNER JOIN selecthr2...
You're using the wrong syntax for an insert from a query result. For this type of insert, you don't need the `VALUES()` portion. As a side-note, you should avoid using `SELECT *` (or, in this case, `a.*, c.*, d.*`) in your `INSERT SELECT` statement, as your temp table would have to be set up just right for that insert...
Issue inserting values with a subquery into temporary table SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have two tables ,location and locationdata. I want to query data from both the tables using join and to store the result in a new table(locationCreatedNew) which is not already present in the MySQL.Can I do this in MySQL? > SELECT location.id,locationdata.name INTO locationCreatedNew FROM > location RIGHT JOIN locat...
Your sample code in OP is syntax in SQL Server, the counter part of that in MySQL is something like: ``` CREATE TABLE locationCreatedNew SELECT * FROM location RIGHT JOIN locationdata ON location.id=locationdata.location_location_id; ```
Use Query like below. ``` create table new_tbl as select col1, col2, col3 from old_tbl t1, old_tbl t2 where condition; ```
Store records in a new table created by a query in mysql
[ "", "mysql", "sql", "database", "" ]
I have been trying to get a query that will take a date field from a table, and only show me the results where the date is over a year old (in respect to the current date). I am using PHPMyAdmin for these queries. The time field's data type is 'date' (yyyy-mm-dd). The code I have so far is ``` SELECT table1.time FRO...
The easiest way would probably be to use [`date_sub`](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub): ``` SELECT table1.time FROM table1 WHERE DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR) > table1.time ```
The easiest way is to check current year and compare data of table with current year data. ``` SELECT table1.time FROM table1 WHERE YEAR(table1.time) = YEAR(CURDATE()) ```
SQL Query that returns dates that are over a year ago from the current date
[ "", "mysql", "sql", "" ]
I am trying to list all the sales, which links with a customer ID, so I expect to see ``` sale ID customerID customerfirstname customerlastname 1 1 J Bloggs 2 2 G Green 3 1 J Bloggs ``` Th...
You are joining on the wrong field - both tables have a column referencing the customer id, which you should use. Additionally, you have a redundant comma after the last item in the select list and are missing one after the first item: ``` SELECT sale.sale_id, customer.customer_id, customer.customer_f...
you need to use `JOIN` to connect the tables. from looking at your tables, it looks like `customer_customer_id` is the column on `sale` table that matches the customer id: ``` SELECT sale.sale_id customer.customer_id , customer.customer_first_name , customer.customer_last_name FROM customer ...
Find all sales made by each customer
[ "", "mysql", "sql", "select", "mysql-workbench", "" ]
I want to select all distinct values of `ColA`, which have at least one out of each element from a given set of values in `ColB` Sample table: ``` ColA ColB A 1 A 2 B 1 C 2 C 2 D NULL E 1 E 2 E 2 E 3 ``` Desired result: all ColA values which have at least once 1 and 2 as ColB...
You can count the values in the `having` clause using conditional logic: ``` having sum(case when colB = 1 then 1 else 0 end) >= 1 and sum(case when colB = 2 then 1 else 0 end) >= 1 ```
`intersect` is one way to do it. ``` SELECT ColA FROM MyTable where colB = 1 intersect SELECT ColA FROM MyTable where colB = 2 ```
GROUP BY ColA having various column values in ColB
[ "", "sql", "t-sql", "sql-server-2014", "" ]
I have two arrays in postgresql: ``` CREATE OR REPLACE FUNCTION func() RETURNS void AS $BODY$ declare first integer[]; second integer[]; array_vb integer[]; array_vb2 integer[]; begin code.... select array_agg(id) into first from a where id = any (array_vb); ...
You can use PostgreSQL [unsent](http://www.postgresql.org/docs/9.2/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) function: ``` SELECT ARRAY(SELECT unnest(first) EXCEPT SELECT unnest(second)) ``` Example: ``` SELECT ARRAY(SELECT unnest(ARRAY[1,10,15,3,7]) EXCEPT SELECT unnest(array[1,3,15,4])) ``` Gives: ``` a...
You can use [`intarray` extension](http://www.postgresql.org/docs/current/static/intarray.html): ``` create extension if not exists intarray; select array[1,10,15,3,7] - array[1,3,15,4] as result; result -------- {7,10} (1 row) ```
Given two arrays how to get items that are not in both?
[ "", "sql", "arrays", "postgresql", "relational-algebra", "" ]
I have a Article table as shown below : ``` create table article( artID int, arttitle varchar(50) ) ``` I have inserted 4 records in as below: ``` insert into article values (1,'abcd'); insert into article values (2,'asfsdf asdf sdf '); insert into article values (3,'asdfasdfa sd '); insert into article values...
If you don't want to use any of the function you can directly check `is null` Check bellow SQL. `select * from article where (@aID is null or artID = @aID) and (@atit is null or arttitle like '%'+ (@atit) +'%')`
This is because both `[]` are special characters and mean that one of the symbols, which is in brackets, must match. In order to fix it - you can escape these. This is what you could do: ``` DECLARE @article TABLE ( artID INT , arttitle VARCHAR(50) ); INSERT INTO @article VALUES (1, 'abcd') , (2, 'asfsdf...
special character in LIKE Operator with COALESCE is not working
[ "", "sql", "sql-server-2008", "stored-procedures", "sql-like", "coalesce", "" ]
I am trying to write a query from a table that contains 'Activities' for customers. Each activity is stored in a single line so if you call a contact and send an email after, it will be in two separate rows. i.e. ``` Contact Employee Date Method Jack John 12/7/15 11:50 Email Jack John ...
The `row_number` window function can help here: ``` select t.contact, t.employee, t.date, t.method from (select *, row_number() over (partition by contact, employee order by case when method = 'Call' then 0 else 1 end, ...
thanks to sstan; this is what I finished with: ``` select t.ContactID, t.Priority, t.ContactedBy, t.ContactedDate, t.ContactMethod from (select FA.ContactID, case when FA.PriorityLevel is null then 2 else FA.PriorityLevel end as [Priority], FA.Employee as [ContactedBy], FA.CreatedDate as [ContactedDate]...
Return record with the max date based on certain criteria
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I stuck on an SQL statement since 2 days now and I hope you can help me with that. The result of my select is a list with 4 attributes A, B, C and D (below is an example list of 5 datasets): ``` 1. A=1 B=100 C=200 D=300 2. A=2 B=200 C=100 D=300 3. A=3 B=300 C=200 D=100 4. A=3 B=100 C=100 D=200 5. A=3 B=300 C=100...
Probably there is an easier way to solve this problem, but this one works: ``` CREATE TEMP TABLE TEST ( A INTEGER, B INTEGER, C INTEGER, D INTEGER ); insert into TEST values (1,1,1,1); insert into TEST values (2,1,5,1); insert into TEST values (2,2,1,1); insert into TEST values (3,1,4,1); insert into TEST values (3,2...
This type of prioritization query is most easily done with `row_number()`, but I don't think Informix supports that. So, one method is to enumerate the rows using a correlated subquery: ``` select t.* from (select t.*, (select count(*) from t t2 where (t2.b > t.b) or ...
Reducing the list of results (SQL)
[ "", "sql", "informix", "" ]
SQL help required. Tables * Person (id, name) * Message (id, text) * PersonMsgResponse (msgID, personID, delMethod, received(Y/N) Structure of the PersonMsgResponse table * MessageID (MsgId) * PersonID (PerID) * MessageDeliveredBy (DelMethod) * Received (Y/N) (Received) Example Rows within PersonMsgResponse table ...
You can accomplish this with 2 inner queries like below. The trick is to include all Persons that have 'N' in received but do not have 'Y'. Message table is technically unnecessary for this example. ``` SELECT p.Name FROM Person p WHERE p.id IN ( SELECT personID FROM P...
You can use `NOT EXISTS`: ``` SELECT Id, Name FROM Person AS p WHERE NOT EXISTS (SELECT 1 FROM PersonMsgResponse AS pmr WHERE p.Id = pmr.personID AND p.Received = 'Y' AND p.MessageID = 1) AND EXISTS (SELECT 1 FROM PersonMsgResponse AS...
SQL Query to obtain result set based on inner join
[ "", "mysql", "sql", "inner-join", "" ]
I am working MS-Access 2007 DB . I am trying to write the query for the Datetime, I want to get records between 14 December and 16 December so I write the bellow query. ``` SELECT * FROM Expense WHERE CreatedDate > #14-Dec-15# and CreatedDate < #16-Dec-15# ``` ( I have to use the two dates for the query.) But It re...
Thanks A Lot guys for your help... I finally ended with the solution given by Darren Bartrup-Cook and Gustav .... My previous query was.... ``` SELECT * FROM Expense WHERE CreatedDate > #14-Dec-15# and CreatedDate < #16-Dec-15# ``` And the New working query is... ``` SELECT * FROM Expense WHERE CDATE(INT(CreatedDa...
As @vkp mentions in the comments, there is a `time` part to a date as well. If it is not defined it defaults to midnight (`00:00:00`). As `14-dec-2015 6:46:56` is after `14-dec-2015 00:00:00` it is included in the result set. You can use `>= 15-dec-15` to get around this, as it will also include records from 15-dec-201...
Giving the wrong records when used datetime parameter in MS Access Query
[ "", "sql", "ms-access", "" ]
I've created the following stored procedure which should return all the location names that had an intersection with polygon group (without distinct... intersection with 3 polygons => 3 names) ``` CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time TIMESTAMP, ...
Your posed answer still has a couple of problems. And you can very well use `RETURNS TABLE()`. Compare: * [plpgsql error "RETURN NEXT cannot have a parameter in function with OUT parameters" in table-returning function](https://stackoverflow.com/questions/14039720/plpgsql-error-return-next-cannot-have-a-parameter-in-f...
You don't need PL/pgSQL for this. The loops are unnecessary and will make everything very slow. As far as I can tell this should do it: ``` CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time TIMESTAMP, end_time TIMESTA...
'syntax error at or near "VARCHAR"' in DECLARE section when trying to create function
[ "", "sql", "postgresql", "plpgsql", "user-defined-functions", "stored-functions", "" ]
I am trying to retrieve data from an XML file. Below is how the XML doc looks and below that is my SQL code. It will run the code and show column headers - but will not populate with any data. What am I missing? ``` <profile xmlns="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12...
Firstly repair the data (`:xs`, `</fighters>`, `</profile>`) ``` <profile xmlns:xs="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z"> <fighters> <fighter id="01585452-852a-4b40-a6dc-fdd04279f02c" height="72" weight="170" reach="" stance="" first_name="Sai" nick_name...
`FROM OPENXML` is not the best approach any more. Try it like this: Just copy this into an empty query window and execute: ``` DECLARE @xml XML= '<profile xmlns="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z"> <fighters> <fighter id="01585452-852a-4b40-a6dc...
read XML in SQL, no data being pulled
[ "", "sql", "xml", "" ]
I have the following two tables: **SURVEY** id: INT (PK) **QUESTIONNAIRE** id: INT (PK) [Screenshot of tables](https://i.stack.imgur.com/7C4VL.png) I want to sellect all surveys along with the number of questionnaires that each survey has so i tried the following query: ``` SELECT s.id, s.title, s.descript...
text is deprecated - try nvarchar(max) or varchar(max) [ntext, text, and image (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms187993.aspx) The left may be the problem but I get you want it. If nvarchar(max) or varchar(max) does not fix it then try this ``` SELECT s.id, s.title, s.description, sq.cc F...
I think you should learn how Group By and aggregate functions work. This would prove greatly effective in your quest to understanding T-SQL. Here is a link that may help you out. [Group By Information](http://www.w3schools.com/sql/sql_groupby.asp) Also, this may not be the case at all but why Text for the description...
Query with left join and count in select works in MySQL but not in MS SQL Server 2012
[ "", "mysql", "sql", "sql-server", "sql-server-2012", "" ]
Suppose I have a table of strings, like this: ``` VAL ----------------- Content of values Values identity Triple combo my combo sub-zero combo ``` I want to find strings which have equal words. The result set should be like ``` VAL MATCHING_VAL ------------------ ------------------ Content of values ...
One method is to use a hack for regular expressions: ``` select t1.val, t2.val from t t1 join t t2 on regexp_like(t1.val, replace(t2.val, ' ', '|'); ``` You might want the case to be identical as well: ``` on regexp_like(lower(t1.val), replace(lower(t2.val), ' ', '|'); ```
You could use a combination of SUBSTRING and LIKE. use charIndex(" ") to split the words up in the substring if thats what you want to do.
SQL: Select strings which have equal words
[ "", "sql", "oracle", "oracle11g", "" ]
Let's say I have a simple table: ``` create table foo { id INTEGER PRIMARY KEY AUTOINCREMENT, bar INTEGER } ``` And I want to insert a new row, such that `id == bar` where value for `id` is chosen by the database, a.k.a. auto-increment. Something like this: ``` INSERT INTO foo (id, bar) VALUES (NULL, id) ``...
In SQLite you can ``` BEGIN TRANSACTION; INSERT INTO foo (id, bar) VALUES (NULL, 0); UPDATE foo SET bar = id WHERE _ROWID_ = last_insert_rowid(); COMMIT; ``` to make sure no other statement gets in the way of your two-statement expression.
You can't have [two auto increment fields](https://stackoverflow.com/a/7352543/1045444). You should use a single auto increment field. Given that both fields would always have the same value for every row, there's no reason to have to such fields anyway. But you can just make trigger which will update another field eq...
Insert into a table and set another column to autoincremented column value
[ "", "sql", "sqlite", "insert", "auto-increment", "" ]
Is there a case where adding DISTINCT would change the results of a SELECT query that uses a GROUP BY clause? [Group by and distinct produce similar execution plans.](http://blog.sqlauthority.com/2007/03/29/sql-server-difference-between-distinct-and-group-by-distinct-vs-group-by/) From my understanding, tables that u...
You are under no obligation to `SELECT` all the `GROUP BY` columns so in this case it would change the results. ``` SELECT COUNT(*) FROM sys.objects GROUP BY schema_id, name ``` --- or ``` SELECT DISTINCT COUNT(*) FROM sys.objects GROUP BY schema_id, name ```
The groups, as defined by the expressions and columns that appear in the `group by` clause, will be unique in the result set. As long as all those same columns are included in the `select` list then `distinct` will be redundant. As noted by Martin Smith this is not required though.
Is SELECT DISTINCT always redundant when using a GROUP BY clause?
[ "", "sql", "sql-server", "select", "group-by", "distinct", "" ]
I know how to find the length of the longest string of a column and how to select it. But what I can't figure out is how to query all columns I tried this in W3School's SQL console ``` SELECT *, MAX(LEN(Address)) as MaxLengthOfAddress FROM Customers; ``` I get this error message > Cannot group on fields selected wi...
You need to find the `MAX(LEN(Address))` and then use that to find records with addresses of that length. E.g., ``` SELECT * FROM Customers WHERE LEN(Address) = ( SELECT MAX(LEN(Address)) FROM Customers ); ``` You didn't tag your question with a particular RDBMS, but depending on what yo...
You need a subquery in your where clause. Try like this: ``` SELECT * FROM Customers WHERE LEN(Adress) >= (SELECT MAX(LEN(Address)) FROM Customers ) ; ```
SQL - How to select all columns of the field with the longest string name
[ "", "sql", "wildcard", "" ]
Assuming a DB like this: ``` Date | Attribute1 | Attribute2 | ... | AttributeN ------------------------------------------------- 1 | A | C | ... | ... 1 | B | C | ... | ... 2 | A | A | ... | ... 2 | B | B | ... | ... 2 | A ...
You can use `HAVING` and `CASE`: ``` SELECT [Date] FROM #tab GROUP BY [Date] HAVING SUM(CASE WHEN Attribute1 = Attribute2 THEN 0 ELSE 1 END) = 0 ``` `LiveDemo` > Otherwise is there a clever way to this using COUNT maybe? Why not :) Version with `COUNT`: ``` SELECT [Date] FROM #tab GROUP BY [Date] HAVING COUNT(CASE...
Perhaps this: ``` select Date from Test Except Select Date from Test where Attribute1 <> Attribute2 ```
Check if two columns are equal for all rows per group
[ "", "sql", "sql-server", "group-by", "equality", "having", "" ]
I have a basic understanding of sql and have built a small database that has to be submitted in 24 hours. I have made a schema in sqlfiddle here <http://www.sqlfiddle.com/#!9/28fcd> I need to run a query that will search for a staff member (from table occurrence or teaching) and return the module\_code and module\_tit...
Query is like: ``` select c.* from course c inner join occurrence o on o.module_code = c.module_code where o.staff = 'Louise Ashby' ``` Based on your schema. However, in a real world application, you wouldn't use such a schema.
``` select `teaching`.staff, `course`.module_code, `course`.module_title from `teaching` inner join `occurrence` on `occurrence`.staff = `teaching`.staff inner join `course` on `course`.module_code = `occurrence`.module_code ```
SQL SELECT query over 2 tables
[ "", "mysql", "sql", "" ]
Two models User and Article have a relation as: * User *has\_one* Article * Article *belongs\_to* User -User has a field called 'status' -Article has a field called 'thing\_i\_need' ``` class User < ActiveRecord::Base has_one :article, foreign_key: request_id # status :integer end class Article < ActiveRecord:...
You can try this ``` User.joins(:article).where(status: 'xyz').pluck('articles.thing_i_need').last ``` I'd recommend reading [select](http://apidock.com/rails/ActiveRecord/QueryMethods/select) & [pluck](http://apidock.com/rails/ActiveRecord/Calculations/pluck) query methods from the doc, earlier I was trying select i...
``` Article.includes('user').where('users.status = ? and articals.request_id = users.request_id', 'xyz').first.thing_i_need ```
Reduce two SQL queries to one in activerecord maybe using joins
[ "", "mysql", "sql", "ruby-on-rails", "activerecord", "rails-activerecord", "" ]
I have to do the below for every teacher. Given a TeacherId, I want to select all students who have this Teacher and have passed the first semester. If all the teachers students have passed, I want to call another stored procedure: ``` EXEC AllTeachersStudentsPassedSemester1 @teacherId ``` The tables are as follows:...
This query should give you all of the teachers that did not have a failing student: ``` Select Distinct S.TeacherId From Students S Where Not Exists ( Select * From CourseSummary C Where C.UserId In ( Select S2.UserId From Students S2 Where S2.Tea...
If I understand your question correctly, you can use a `join` with aggregation to get the list of teachers. Then you would need to use a `cursor` to call a separate stored procedure passing in each teacher's id. Here is the `sql` to get the teachers: ``` select s.teacherid from students s join coursesummary cs on...
How to check if all of a Teachers students have met a requirement
[ "", "sql", "sql-server", "" ]
I want to query data in mysql like: ``` $cid=$_POST["cid"]; $room_id=$_POST["room_id"]; $time=$_POST["time"]; $reuslt=$this->db-query("SELECT * FROM mytable WHERE if($cid is not null){then check cid=$cid} else{don't check} AND if($room_id is not null){then check room_id=$room_id} else{don't check} AND if($time is not...
So if you wanted to use an SQL if|else statement, look at something like [Using an IF Statement in a MySQL SELECT query](https://stackoverflow.com/questions/8444570/using-an-if-statement-in-a-mysql-select-query), or [If else on WHERE clause](https://stackoverflow.com/questions/15162404/if-else-on-where-clause). Some o...
You can use `1=1` as a placeholder in an `IF` function in a `WHERE` clause: ``` $query = "SELECT * FROM mytable WHERE IF('$cid' != '', cid='$cid', 1=1) AND IF('$room_id' != '', room_id='$room_id', 1=1) AND IF('$time' != '', time='$time', 1=1)" $result=$this->db->query($query); ``` I don't know how your fr...
How to use if else in mysql where clause
[ "", "mysql", "sql", "codeigniter", "" ]
Here is the table: ``` ([TeamA],[TeamB],[Win],[date]) ('KKR','HYD','KKR',1), ('KKR','MUM','MUM',2), ('RCB','HYD','HYD',3), ('DEL','PUB','PUB',4), ('RR','PUB','RR',4), ('RR','DEL','RR',5), ('RCB','CSK','CSK',6), ('RR','CSK','RR',7), ('CSK','MUM','MUM',7), ('MUM','DEL','MUM',8), ('HYD','PUNE','PUNE',9), ('PUB','DE...
My approach (probably it can be done in cleaner way): ``` WITH cte AS ( SELECT TeamA AS team FROM #tab UNION SELECT TeamB FROM #tab ), cte2 AS ( SELECT c.team ,[opponent] = CASE WHEN c.team = t.teamA THEN t.teamB ELSE t.teamA END ,t.[win] ,t.[day] ,[is_winner] = CASE WHEN c.team = t.[...
One more possible way of solving this without using CTE: ``` create table #a ( teama varchar(10), teamb varchar(10), win varchar(10), dat int) insert into #a values ('KKR','HYD','KKR',1), ('KKR','MUM','MUM',2), ('RCB','HYD','HYD',3), ('DEL','PUB','PUB',4), ('RR','PUB','RR',4), ('RR','DEL','RR',5), ('RCB','CSK','...
How to get three wins in a row
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Here is my table ``` Equipmentid Application Value =========== =========== ===== k001 THK True k001 BHK False k001 KHK True ``` Here is what I expected: ``` Equipmentid THK BHK KHK =========== === === === k001 True Fa...
Try this one. ``` SELECT EQUIPMENTID, max(case when APPLICATION = 'THK' then VALUE end) as "THK", max(case when APPLICATION = 'BHK' then VALUE end) as "BHK", max(case when APPLICATION = 'KHK' then VALUE end) as "KHK" FROM [tablename] group by EQUIPMENTID; ```
Hi try using PIVOT, ``` WITH x(equipment_id, application, VALUE ) AS (SELECT 'k001', 'THK', 'TRUE' FROM DUAL UNION ALL SELECT 'k001', 'BHK', 'FALSE' FROM DUAL UNION ALL SELECT 'k001', 'KHK', 'TRUE' FROM DUAL UNION ALL SELECT 'k002', 'KHK', 'FALSE' FROM DUAL UNION ALL SELECT '...
How to transpose dynamically in Oracle
[ "", "sql", "oracle", "oracle11g", "transpose", "" ]
How to display first name, last name and salary of all subordinates from HR on Oracle? I have: ``` SELECT J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY, (SELECT SUM(EMPLOYEES.SALARY) FROM EMPLOYEES) FROM JOBS J LEFT JOIN EMPLOYEES E ON J.JOB_ID = E.JOB_ID GROUP BY J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY ...
So, if I got this right, you want your last column to be the total salary of all the subordinate employees, both direct and indirect. If so, you can use a `connect by` clause in the subquery to get that information. Try something like this: ``` SELECT j.job_title, e.first_name. e.last_name, e.sal...
I think you're looking for something like this: ``` SELECT J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY, (SELECT SUM(EMPLOYEES.SALARY) FROM EMPLOYEES where manager_id = e.employee_id) FROM JOBS J LEFT JOIN EMPLOYEES E ON J.JOB_ID = E.JOB_ID GROUP BY J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E....
How to display first name, last name and salary of all subordinates from HR. Oracle
[ "", "sql", "oracle", "oracle11g", "" ]
I'd like to know difference between `rowID` and `rowNUM` And how to see both of these in our table. when I execute this: ``` SELECT * FROM emp WHERE rownum=1 ``` It returns one query but when I do the same for rowid it says > inconsistent datatypes: expected ROWID got NUMBER And even in some of the tables, rownum...
Both, ROWNUM and ROWID are pseudo columns. **Rowid** > For each row in the database, the ROWID pseudo column returns the > address of the row. An example query would be: ``` SELECT ROWID, last_name FROM employees WHERE department_id = 20; ``` More info on rowid here: <https://docs.oracle.com/cd/B19306_01/s...
**Rownum (numeric)** = Generated Sequence Number of your output. **Rowid (hexadecimal)** = Generated automatically at the time of insertion of row. ``` SELECT rowid,rownum fROM EMP ROWID ROWNUM ----- ---------------------- AAAR4AAAFAAGzg7AAA, 1 AAAR4AAAFAAGzg7AAB, 2 ...
What is rowID & rowNum (ROWID vs ROWNUM)
[ "", "sql", "oracle10g", "rownum", "rowid", "" ]
I have following DQL query ``` SELECT ps.id, MAX(ps.dueDate) as due_date, u.firstName as first_name, u.lastName as last_name, u.email, IDENTITY(ps.loanApplication) as loan_application_id, DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE()) as diff FROM Loan\Entity\PaymentSchedule ps LEFT JOIN ...
If you want to use the alias in your WHERE clause you need a `sub-select`. ``` select * from (SELECT p0_.id AS id_0, MAX(p0_.due_date) AS sclr_1, u1_.first_name AS first_name_2, u1_.last_name AS last_name_3, u1_.email AS email_4, p0_.loan_application_id AS sclr_5, DATEDIFF(MAX(p0_.due_date...
You cannot use an alias (on the final result fields) in the `WHERE` clause; however, at least with MySQL, you may use a `HAVING` clause without needing a `GROUP BY`.
Unknown column where clause
[ "", "mysql", "sql", "doctrine-orm", "dql", "" ]
I have 2 large tables that I am trying to join in order to group the first records based on a field from the second table. The left table has approx.50 mil records of events, the right table has approx.35 mil records of monthly intervals. The monthly intervals are at subjID level, thus I cannot reduce the size of the r...
If you have enough memory and you only need the `enddate` from `monthlyTable`, you might find that a format merge is a more efficient way of doing this. However, if both datasets are large, there's only so much optimisation you can hope for as you always have to do at least full read of each. ``` data t_format(keep = ...
The best index for your query is a composite index on `monthlyTable(subjId, startDate, endDate)`. I'm not sure if it will be a big improvement in terms of performance in SAS, however.
Optimize SAS Proc SQL query
[ "", "sql", "join", "optimization", "sas", "proc", "" ]
``` create table #middle ( A INT, B INT, C INT ) INSERT INTO #middle (A,B,C) VALUES (7,6,2),(1,0,8),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16) ;WITH MIDS AS (SELECT *, Row_number() OVER ( ORDER BY a,...
You can use OFFSET and FETCH ``` select * from #middle order by a, b, c desc offset (select count(*) / 2 - (case when count(*) % 2 = 0 then 1 else 0 end) from #middle) rows fetch next (select 2 - (count(*) % 2) from #middle) rows only ```
There are many ways to get the median in SQL. Here is a simple way: ``` select h.* from (select h.*, row_number() over (order by a, b, c desc) as seqnum, count(*) over () as cnt from #highest h ) h where 2 * rn in (cnt, cnt - 1, cnt + 1); ``` For an even number of records, you will get two row...
How to get the middle most record(s) from a group of data in sql
[ "", "sql", "sql-server", "" ]
I just started using PL/SQL Developer and I've tried to Google this issue for hours to no avail. Here is my Query: ``` SELECT "STATION_CODE", "STATUS", COUNT(1) FROM "Table" "R" WHERE "STATUS" IN ('LOOKUP CLEAR') AND NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL')) AND "CALL_DATE" BETWEEN TO_DATE('07/12...
### It's called `GROUPING SETS` The simplest solution would be to use [`GROUPING SETS`](https://docs.oracle.com/database/121/DWHSG/aggreg.htm#DWHSG8631) in your `GROUP BY` clause: ``` SELECT DECODE(GROUPING_ID("STATION_CODE"), 0, "STATION_CODE", 'Sum'), "STATUS", COUNT(1) FROM "Table" "R" WHERE "STATUS" IN ('LOOKUP C...
Remove the `group by` and just do an overall count: ``` SELECT COUNT(1) FROM "Table" "R" WHERE "STATUS" IN ('LOOKUP CLEAR') AND NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL')) AND "CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY') AND TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:...
How to sum a count in SQL
[ "", "sql", "oracle", "group-by", "" ]
I'm not sure if I'm asking this right, but I am trying to have 1 row contain all the data for each "policy". The problem is, only 1 "insured name" is given per row. Example table: [![enter image description here](https://i.stack.imgur.com/WFKws.png)](https://i.stack.imgur.com/WFKws.png) I need to get the following re...
I added effective date to the query as I could see a composite primary key including both policy number and effective date. This assumes a view on the data would be acceptable with changing existing table structure and data. ``` SELECT a.PolicyNumber, a.effecitveDate a.insuredName as InsuredName1, b.insur...
I believe you want to use the following in some fashion: ``` SELECT DISTINCT a.insuredName, b.insuredName FROM table a INNER JOIN table b ON a.policyNumber = b.policyNumber ``` if effective date is also a consideration: ``` ... On a.policyNumber = b.policyNumber And a.effectiveDate = ...
Combine columns a, b, c if column x is duplicate record - SQL
[ "", "sql", "netezza", "" ]
My Database class is this, when i call `deleteEntry`, it does not remove 0 index , this is database class method ``` public int deleteEntry(String id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); //String id=String.valueOf(ID); String where="ID=?"; int numberOFEntriesDelet...
You can try like this: ``` //---deletes a particular entry--- public int deleteEntry(String id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); return db.delete("TIME", "ID = " + id, null) ; } ``` By the way, make sure "TIME" is your tablename and you also close the database.
Try passing the position instead of an id: ``` list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("Clicked item id", " " + id); Log.d("Clicked item position", " " + position...
delete zero index of listview which populated from database Android
[ "", "android", "sql", "database", "listview", "" ]
I am using MS SQL Server 2012 Express Advanced Edition. My current table structure of one of the accounts table with data is as follows. ``` PARTY DEBIT CREDIT ---------------------------------------- A 1000 NULL B NULL 2500 C 2000 NULL A ...
If you have some column to maintain the ordering, you could try an analytic function along these lines: get the total for the group (party), then use that as a subquery to display only the balance for the first item in the group. I tried this with Postgresql, you would need to check the syntax for your dbms. Inner que...
What you want to achieve doesn't make sense to me. But if you still want to do that, then you need to have a primary key in your balance table. For the example I'm taking ID field of type int as a primary key. Using below sql query you can achieve your desired result: ``` SELECT A.PARTY, A.DEBIT, A.CREDIT, B.BALANCE ...
SQL Server Query For Balance to appear only once if party name occurs multiple times
[ "", "sql", "sql-server-2012", "" ]
I have a time interval in the format '88:52:57' I need to convert it into a decimal hours in the format 88.88 How can I do this? I have the data initially loaded as a varchar
You can use left, right and substring to extract the values and then do some calculations. ``` declare @S varchar(8) = '88:52:57'; select left(@S, 2) + substring(@S, 4, 2)/60.0 + right(@S, 2)/60.0/60.0; ``` If you not always have two digit values you can use parsename to get the values instead. ``` declare @S varch...
Try this, solution is based on conversions, making it safe, if the format is always (h)h:mi:ss: ``` DECLARE @S varchar(8) = '88:52:57'; SELECT CAST(REPLACE(left(@S, 2), ':', '') as int)+ CAST(CAST(CAST('0:'+RIGHT(@S, 5) as datetime) as decimal(10,10)) * 24 as decimal(2,2)) ``` Result: ``` 88.88 ```
Convert time interval into decimal hours in SQL Server
[ "", "sql", "sql-server", "" ]
I am inserting data in table with current system time like `System.currentTimeMillis()`. So, while getting data I need to take last 3 hours data only. Following link not help me. because this link using specific date format which I don't have. [Getting data according to last hours from sqlite](https://stackoverflow....
You can get TimeStamp of Time 3 Hours back using following ``` Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -3); Date threeHourBack = cal.getTime(); ``` Then you can pass `threeHourBack.getTime()` to the query. Or You can do this in SQLite ``` SELECT * FROM Table1 where datetime(timestamp) >=dateti...
there could be other methods. but I think this will work for you. ``` SELECT * FROM Table1 where timestamp >= (System.currentTimeMillis()-108000000) ``` subtract 3 hours from current time and and search for time grater than that.
How to get Last 3 hours data from SQLite
[ "", "android", "sql", "select", "timestamp", "" ]
I'm having a hard time solving this, i hope someone can help me out with some tips or advice. I have a Table in SQL with 3 columns: ``` Pencil Sales Notebook Sales Pen Sales 1 2 3 9 5 6 7 8 9 ``` I made a query using ...
``` select * from ( select 'Pencil Sales' as Name, sum(pencilsales) as sales from table1 union all select 'Notebook Sales', sum(notebooksales) from table1 union all select 'Pen Sales', sum(pensales) from table1 ) t order by sales desc ```
This is a pretty good candidate for UNPIVOT ``` SELECT SUM(Sales) Sales, [Name] FROM Table1 UNPIVOT ( Sales FOR [Name] IN ([pencilsales], [notebooksales], [pensales]) ) up GROUP BY [Name] ```
Merge multiple columns in one single column SQL
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
In SQL,I am trying to compare two numbers in the same field. Both numbers contain different information, but for some technical reason they are same. The problem is when exist one sub-string of length 5 and another of length 4 and the last 4 digits of both are same.I want to get the first one with length 5. Example: ...
Try this: ``` SELECT Id ,Number ,Description FROM ( SELECT Id ,Number ,Description ,rank() OVER (PARTITION BY right(cast([Number] AS VARCHAR(20)), 4) ORDER BY Number DESC) AS Ranking FROM YourTable ) InnerTable WHERE ranking = 1 ```
So you need to join using last 4 digits. You could do this by using simple `MOD` operator. It's used as a percentage sign in SQL Server. ``` SELECT 12345 % 10000; ``` This outputs `2345`. Exactly what we are looking for. So we could build the following query to use that calculation: ``` DECLARE @Test TABLE ( ID...
Compare two number SQL
[ "", "sql", "sql-server", "case", "common-table-expression", "" ]
I've been trying to split a string value in my query to return the first part of a two part postcode in a new column. Some values have only the first part, and some have both. After a bit of searching I found this code: ``` SELECT TblPLSSU.PLSSUPostcode ,SUBSTRING(TblPLSSU.PLSSUPostcode, 1, CHARINDEX(' ', TblPLS...
Use `case` to pick up post codes as-is when they don't have a space separated value. ``` SELECT PLSSUPostcode ,case when CHARINDEX(' ', PLSSUPostcode) > 0 then SUBSTRING(PLSSUPostcode, 1, CHARINDEX(' ', PLSSUPostcode)) else PLSSUPostcode end AS PCode FROM TblPostcodes ```
Use `case` as well: ``` SELECT TblPLSSU.PLSSUPostcode, (CASE WHEN TblPLSSU.PLSSUPostcode LIKE '% %' THEN SUBSTRING(TblPLSSU.PLSSUPostcode, 1, CHARINDEX(' ', TblPLSSU.PLSSUPostcode)) END) AS PCode FROM . . . ```
SQl string split (parse) on space where some field values have no space
[ "", "sql", "sql-server-2008", "" ]
I don't want the query to select anything if the where clause is not fullfilled, but maybe i am missing something. Following is the query i am using ``` SELECT one.id_user, integration, data FROM tableOne one LEFT JOIN tableTwo two ON two.id_user = one.id_user AND two.integration IN ('office', 'Office') WHERE one.stat...
From what I see you made 2 errornous assumptions there. The first is the sql statement is NOT a left join. As strange as it sounds. The reason behind this is that you use the 2nd table that is joined via left join in the where statement. This transforms the whole left join into an inner form instead. The second assum...
Try this: ``` SELECT one.id_user, integration, data FROM tableOne ONE INNER JOIN tableTwo two ON two.id_user = one.id_user WHERE one.state IN ('NEW', 'PAUSED') AND two.integration IN ('office', 'Office') GROUP BY one.id_user; ```
How can i use left join in mysql
[ "", "mysql", "sql", "select", "join", "" ]
Sorry I don't have better words to title my questions but essentially I am looking for an implementation of CASE/AND...OR statement in the filter condition where if the value of the particular ID is NOT NULL and greater than 0, then only the condition for that ID would be considered otherwise the condition for that ID ...
I think you were shooting for this: ``` case when @sub_emp_id > 0 /* not null is also implied */ then case when a.sub_emp_id = @sub_emp_id then 1 else 0 end else 1 end = 1 ``` And I think these are equivalent alternatives: ``` not (@sub_emp_id > 0 and a.sub_emp_id <> @sub_emp_id) coalesce(@sub_emp_id, 0)...
If I understand you correctly, you'll want your filter on `sub_emp_id` to look like this: ``` ... and (@sub_emp_id is null or @sub_emp_id <= 0 or a.sub_temp_id = @sub_emp_id) ```
SQL - CASE statement in filter with optional use
[ "", "sql", "oracle", "case", "where-clause", "" ]
Table schema: ``` CREATE TABLE TRANSACTIONDETAILS ( TransNo CHAR(15), Serial INT, Project CHAR(3) ) ``` Dataset: ``` +-----------------+--------+---------+ | TransNo | Serial | Project | +-----------------+--------+---------+ | A00000000000001 | 1 | 100 | | A00000000000001 | 2 | ...
You can use subquery to get the list of `TransNo` that have more than one distinct project and then filter initial list only by results from subquery: ``` SELECT TransNo, Serial, Project FROM TRANSACTIONDETAILS WHERE TransNo IN ( SELECT TransNo FROM TRANSACTIONDETAILS GROUP BY TransNo HAVING COUNT(DIST...
What you'll want to do is get a table with the duplicates. `SELECT TransNo, Project FROM TRANSACTIONDETAILS GROUP BY TransNo, Project HAVING COUNT(1) > 1` then you'll want to join back to the table. Here's the complete query: `SELECT A.TransNo, A.Serial, A.Project FROM TRANSACTIONDETAILS A INNER JOIN ( SELECT Tra...
Complex SELECT Operation in SQL Server 2012 and later
[ "", "sql", "sql-server-2012", "" ]
I know that SQL query will use query cache to receive data instead of reprocess all of the data. Here the question I would like to ask, I working with a server of database and I'm one of the developer that working on it and I need to do performance testing on queries that i handling If I clear the query cache example...
Two clarifications to begin with: * MySQL query cache is a server-side feature, there's no such thing as "local cache". You're probably confused by the `LOCAL` keyword in `FLUSH` command. As [docs](https://dev.mysql.com/doc/refman/5.7/en/flush.html) explain it's just an alias for `NO_WRITE_TO_BINLOG` (thus it's relate...
Try using the SQL\_NO\_CACHE option in your query.This will stop MySQL caching the results ``` SELECT SQL_NO_CACHE * FROM TABLE ```
SQL Query Cache
[ "", "mysql", "sql", "caching", "" ]
I'm trying to get the results from a table such that they are limited by the number of similar field values. For example, here are some sample records: ``` FieldValue (nvarchar) ---------- id1/mode3/path id2/mode2/path id3/mode3/path id4/mode1/path id5/mode3/path id6/mode2/path id7/mode2/path id8/mode3/path ``` In wh...
You can use windowed function and string manipulation function to split data: ``` WITH cte AS ( SELECT FieldValue ,[id] = LEFT(FieldValue, CHARINDEX('/', FieldValue)-1) ,[mode] = SUBSTRING(FieldValue, CHARINDEX('/', FieldValue)+1, ...
Lad2025's answer does the job, but I would consider improving your table design (schema), if possible. In order to avoid computing those substrings and ordering based on it (it is expensive for large data), you can add new columns to the table. They can be computed when FieldValue is inserted or, if this is not possib...
Limit results by field value using TSQL
[ "", "sql", "sql-server", "t-sql", "" ]
``` Create Table Billing3 ( billingId int primary key, FoodCharge float DEFAULT 0, DoctorCharge float DEFAULT 0, TestCharge float DEFAULT 0, OperationCharge float DEFAULT 0, RoomCharge float DEFAULT 0, Total float DEFAULT (FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) ) ```
Alternatively, you can set up a MySQL [insert trigger](http://www.w3resource.com/mysql/mysql-triggers.php). But usually, you want to keep calculations in queries as you save on storage and avoid maintenance on a programming object. Plus, if one of the charges updates values, you would then need an update trigger. ``` ...
MySQL does not support calculated columns. You can use a view for this purpose: ``` create view v_billing3 as select b.*, (FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) as total from billing3 b; ``` Also, don't store numbers as floating points. Instead, use the fixed point ...
How to create table having one column as sum of other columns?
[ "", "mysql", "sql", "database", "" ]
We're trying to run an outer join between table A on both tables B and C but get the error: > ORA-01417: a table may be outer joined to at most one other table How can we get this to work? Query: ``` select a.xxx, a.yyy, b.col1, c.col1 from a, b, c where a.xxx = b.xxx (+) and a.yyy = b.yyy (+) and a.xxx = c.xxx (+...
Please refrain from using comma in the from clause and use the JOIN clause instead. Try using this: ``` select a.xxx, a.yyy, b.col1, c.col1 from a LEFT JOIN b ON a.xxx = b.xxx AND a.yyy = b.yyy LEFT JOIN c ON a.xxx = c.xxx AND a.yyy = c.yyy ```
Use proper explicit `join` syntax. I think the following is probably what you want to do: ``` select a.xxx, a.yyy, b.col1, c.col1 from a left join b on a.xxx = b.xxx and a.yyy = b.yyy left join c on a.xxx = c.xxx and a.yyy = c.yyy; ```
Outer join between three tables causing Oracle ORA-01417 error
[ "", "sql", "oracle", "outer-join", "" ]
I have **users** and **message\_threads** tables. ``` thread_message tables Id | ToUserId | FromUserId ---------------------------------- 1 | 1 | 2 2 | 2 | 3 users Table Id | Name ----------------- 1 | Ali 2 | Mahdi 3 |...
``` (select t.*, u.Name from thread_message t left join users u on FromUserId=u.Id where ToUserId=1) union (select t.*, u.Name from thread_message t left join users u on ToUserId=u.Id where FromUserId=1) ```
Try this: ``` SELECT T.Id, T.ToUserId, T.FromUserId, (CASE WHEN T.ToUserId = tu.Id THEN fu.Name WHEN T.FromUserId = tu.Id THEN tu.Name ELSE '' END) Name FROM thread_message T LEFT OUTER JOIN users tu ON T.ToUserId = tu.Id LEFT OUTER JOIN users fu ON T.FromUserId = tu.Id WHERE 1 IN (T.ToUse...
Select and join from to tables in mysql
[ "", "mysql", "sql", "database", "select", "join", "" ]
Below is my query: **select c1, c2, c3, c4, c5 from table1 where c1 =0** //Condition 1 **AND c2="abc"** //Condition 2 **AND c3="xxx"** //Condition 3 **AND c4 = 5** //Condition 4 Here as we know that condition 2 will be applied on result data given by condition 1, condition 3 will be applied on on result...
I got one simple solution for this and it is working in my scenario. Also I am able to reduce time for query execution on my big data. Defiantly two queries will be executed but i find this proper solution. I used simple Union query. **select c1, c2, c3, c4, c5 from table1 where c1 =0** //Condition 1 **AND c2="abc"...
As far as I can see you want to have **condition 3** optional. That can be done, but would hardly be an efficient solution: ``` Select c1, c2, c3, c4, c5 From table1 Where c1 = 0 AND c2 = "abc" AND (c3 = "xxx" OR NOT Exists (Select '*' From table1 Where c1 = 0 AND c2 = "abc" AND c3 = "xxx") ) AND c4...
output with condition based sub query in mysql
[ "", "mysql", "sql", "subquery", "conditional-statements", "inner-query", "" ]
While editing some queries to add alternatives for columns without values, I accidentally wrote something like this (here is the simplyfied version): ``` SELECT id, (SELECT name) FROM t ``` To my surprise, MySQL didn't throw any error, but completed the query giving my expected results (the `name` column values). I t...
This is the default behavior for the SQL language and it is defined on the [SQL ANSI 2011 over ISO/IEC 9075-1:2011(en)](https://www.iso.org/obp/ui/#iso:std:iso-iec:9075:-1:ed-4:v1:en) documentation. Unfortunately it is not open. This behavior is described on the section 4.11 SQL-Statements. This behavior happens becau...
What you within your first query is a correlated subquery which simply returns the **name** column from the table **t**. no actual subquery needs to run here (which is what your EXPLAIN is telling you). > In a SQL database query, a correlated subquery (also known as a > synchronized subquery) is a subquery (a query ne...
Sql syntax: select without from clause as subquery in select (subselect)
[ "", "mysql", "sql", "mysql-5.6", "" ]
I have a table of messages that contains a message id field, a language id field and a text field. An app needs to display a message based on the id and language which together form the unique key. All messages exist for language `EN`, but not all have been translated to other languages. So for English there will alway...
You can use a `LEFT JOIN` and `ISNULL` to achieve this ``` SELECT ISNULL(fr.message, en.message) AS message FROM message_table en LEFT JOIN message_table fr ON fr.message_id = en.message_id AND fr.language = 'French' WHERE en.message_id = 17 AND en.language = 'English' ```
A simple approach just uses `order by` for prioritization: ``` select top 1 mt.* from message_table mt where mt.message_id = 17 and mt.language in ('French', 'English') order by (case when mt.language = 'French' then 1 else 2 end); ``` For a single message, performance is optimized with an index on `message_table(mes...
SQL Server: how to return 1 row as default if condition not met
[ "", "sql", "sql-server", "database", "" ]
Can someone help me to figure out how is the best way to do this? I have a list of people with cars. I need to execute a query that will return people that have a type of car and don't have another type at the same time. Here is my example: ``` ID Name CarType ----------- ---------- ---------- 1 ...
Here's one way ``` SELECT Id, Name FROM Cars WHERE CarType = 'SUV' EXCEPT SELECT Id, Name FROM Cars WHERE CarType = 'MINI VAN' ``` Or another ``` SELECT Id, Name FROM Cars WHERE CarType IN ('SUV', 'MINI VAN') GROUP BY Id, Name HAVING MIN(CarType) = 'SUV' ``` Or a more generic version that addresses the different...
This is normally accomplished with a single query in standard SQL, using `NOT EXISTS`: ``` SELECT * FROM mytable AS t1 WHERE CarType = 'SUV' AND NOT EXISTS (SELECT * FROM mytable AS t2 WHERE t1.Name = t2.Name AND t2.CarType = 'MINI VAN') ``` The above query will select all ...
How to have IN and NOT IN at same time
[ "", "sql", "sql-server", "" ]
I am building a report based on the results of some SQL. There is an event that has 3 judges scoring. I am running into an issue with a specific fight in the night (The event is a fight). Here is my code: ``` USE DatabaseName; DECLARE @EventID INT = ; DECLARE @FightID INT = ; ----Judge 1 SELECT DISTINCT JudgeN...
On your joins for the #MQ1 table add RoundNumber. This issue is if you join just on fightid if you get 27 rows. Because the fightids match all rows. ``` INNER JOIN #Judge1 ON #Judge1.FightID = FI.FightID INNER JOIN #Judge2 ON #Judge2.FightID = FI.FightID AND #Judge2.RoundNumber = #Judge1.RoundNumber INNE...
Exclude some of the columns you return in the distinct clause for testing. This way you might discover that the problem is in columns that use computation.
Can't figure out why SQL is returning more rows than expected
[ "", "sql", "sql-server", "" ]
I want to find all lines of data that have a value, say 'N/A' I want to then update ALL the lines of data where they have the same CommonID into the NewDataHere Column so in the example below ID 1 and 2 would be affected I am doing this in a stored procedure **Code for far:** ``` DECLARE @sqlPRatingChange NVARCHAR(...
Why are you using dynamic SQL? Your query seems close enough. It just needs a correlation clause: ``` UPDATE TblAsbestos SET NewDataHere = 'NA' WHERE (SELECT ID FROM TBLASBESTOS a2 WHERE VALUE = 'N/A' AND TblAsbestos.id = a2.id); ``` In SQL Server, I might be inclined to do this using a CTE and window functi...
This should possibly be a comment on Gordon's answer, but it got too long and the formatting that an answer affords helps... The incorrect syntax error is because in SQL Server you cannot alias the target of an update statement (not to be confused with using an alias as the target which is allowed). The where clause i...
Update Multiple ID's based on field value
[ "", "sql", "sql-server", "sql-server-2012", "" ]
sql update depending on the current value. a table(id,color,code) value for code are (a,b,c,...) How can i change all a to AA and c to CC without accessing a record more than once. I think its like getting code for each color and if a -> AA and if c -> CC
Use `Case statement` ``` update yourtable set code = case code when 'a' then 'AA' when 'c' then 'CC' END Where code in('a','c') ```
Here is an amusing alternative: ``` update t set code = upper(code) || upper(code) where code in ('a', 'c'); ```
update by accessing record only once.
[ "", "sql", "oracle", "" ]
This is very simple but somehow I'm doing something wrong with this query on my database. I have this query below: ``` SELECT login FROM accounts WHERE login = "loginname"; ``` When I execute this query the result I get is this: ``` column "loginname" does not exist ``` This is a no brainer, why is this query not ...
Try with single quotes `''` if you are trying to match a string ``` SELECT login FROM accounts WHERE login = 'loginname'; ``` Check the [documentation](http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS) > There is a second kind of identifier: the delimited identifier or > quo...
Double quotes (`"`) are used to refer to object names, in a case sensitive way. In this case, `"loginname"` is interpreted as a column name, and the query fails, since there is no such column. In order to refer to a string literal, you should use single quotes (`'`): ``` SELECT login FROM accounts WHERE login = 'login...
Can someone help point out to me what is wrong with this no brainer WHERE clause?
[ "", "sql", "postgresql", "select", "syntax-error", "" ]
I have a program that is linked to a sql DB, with 2 tables - `Customers` and `SInfo`. Customers has the normal columns: ``` CUSTOMERID (Primary Key) FIRSTNAME LASTNAME EMAIL ``` SInfo has details about the Customer: ``` SSheetID (Primary Key) CustomerID SerialNumber ``` When I use the query builder in .net, ...
Various options... via `distinct`: ``` select distinct c.* -- or better: more specific c. columns from SInfo s inner join Customers c on c.CUSTOMERID = s.CustomerID where s.SerialNumber = @serial ``` via `exists`: ``` select * from Customers c where exists ( select 1 from SInfo s where s.CustomerID = c.CUST...
You can use natural join for this case because when you use natural join, it will match people with the same Customer ID and then use GROUP BY so it will show the name one time. ``` select first_name, last_name, email from customer natural join Sinfo group by customerID, first_name, last_name, email ```
SQL Group By, Distinct confusion
[ "", "sql", ".net", "" ]
I am using the below query to get total amount after a discount. My issue is when the discount is equal to zero, the total amount becomes zero. How can I resolve this issue? ``` SELECT CAST(SUM(Quantity * UnitPrice * (Discount / 100)) AS varchar(50)) FROM Stock_Purchase_Details ```
simple case construct ``` unitPrice * case when discount > 0 then (discount / 100) else 1 end ``` That's for the code you posted. Normally, a discounted price is ``` unitPrice * ((100 - discount) / 100) ```
If you want final amount after discount, you should use ``` CAST(SUM(Quantity * UnitPrice * (1-(Discount/100)) AS VARCHAR(50)) ``` This will give you the amount after discount. Your current formula gives you the amount discounted, not the amount after discount
SQL query issue with zero discount
[ "", "sql", "sql-server", "sql-server-2008", "" ]
SQL amateur here. I have a table containing voucher codes: ``` id voucherCode UserId ------------------------ 1 abcde 13 2 bcdef 11 3 cdefg 4 defgh ``` Now if one of my users qualify for a voucher code, I get one from my table: ``` SELECT TOP 1 * FROM tableName WHERE UserId IS NULL; UPDATE t...
I guess you can do it in opposite order; I mean, you `UPDATE` the table with the user ID and then `SELECT` the voucherCode. This way you shouldn't have any problem.
You can do this by returning the value in the `update` statement, using the `output` clause: ``` declare @ids table (userid int); with toupdate as ( SELECT TOP 1 * FROM tableName WHERE UserId IS NULL ) UPDATE toupdate SET UserId = @UserId OUTPUT inserted.UserId INTO @ids; ```
How to lock a row so that a select returns a row exactly once?
[ "", "sql", "sql-server", "database", "t-sql", "sql-server-2014", "" ]
I want to find age, for example, between 20 to 30 from my table from the current system date. Below is my table details: ``` GivenName DOB Raj 1950-06-06 00:00:00.000 Rahul 1951-01-06 00:00:00.000 Mohan 1952-11-09 00:00:00.000 khan 1953-07-24 00:00:00.000 ```
> for example, between 20 to 30 Use [`DATEDIFF`](https://msdn.microsoft.com/en-us/library/ms189794(v=sql.120).aspx): ``` SELECT Age = DATEDIFF(year, DOB, GetDate()), Between20_30 = CASE WHEN DATEDIFF(year, DOB, GetDate()) BETWEEN 20 AND 30 Then 'yes' ELSE 'no' END FROM dbo.Table1 ``` [**...
``` select GivenName,Age = DATEDIFF(year, DOB, GetDate()) FROM [dbo].[AgeCalc] where DATEDIFF(year, DOB, GetDate()) BETWEEN 20 AND 30 ```
SQL Select query using current date time to get the users ages?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm having beginner troubles with MySQL. I'm trying to build a DB of parts which have a ten digit alphanumeric part number based on the department and class of a part. For example, a part from department "Foo" of class "Bar" might be *FOBAR10000*. The departments and classes are stored in their own tables, so I store t...
This is an update on joined tables. Try this Query: ``` UPDATE partslist pl JOIN partdepartments pd ON pl.PartDeptId = pd.idPartDepartments JOIN partclasses pc ON pl.PartClassID = pc.idPartClasses SET pl.PartFullAlphaID = concat(pd.DeptShortName, pc.ClassShortName, pl.PartIntID) ``` also look at [stackoverf...
Have you tried selecting the results out into variables? ``` DECLARE @ResultID varchar(10), @FullName varchar(100) SELECT @ResultID = pl.idPartsList, @FullName = concat(pd.DeptShortName, pc.ClassShortName,pl.PartIntID) FROM partdepartments pd, partclasses pc, partslist pl WHERE pl.PartDeptId =...
How do I assign this concatenated value back to its table?
[ "", "mysql", "sql", "database", "" ]
Is it accurate to say that of the existing graph query languages (Cypher, Datalog, Sparql etc) Gremlin is the only one that's Turing complete? In case it matters, I'm not looking for edge cases like the Turing completeness proof of Magic: the Gathering; the intent of my question is whether Gremlin is the only graph qu...
I'm not sure about what you include in the `etc.`. But I think your statement is correct. As you say that you are not looking for edge cases or exotic manipulation of the language. 1. [Cypher is not turing complete](https://www.quora.com/Should-I-learn-Cypher-or-Gremlin-for-operating-a-Neo4j-database) 2. [SQL is not p...
* cypher is not Turing complete * GSQL is Turing complete * Gremlin is Turing complete. See the detailed comparison of them at this white paper <https://info.tigergraph.com/gsql>
Turing complete graph query languages
[ "", "sql", "gremlin", "graph-traversal", "datalog", "turing-complete", "" ]
Struggling with a create table statement which is based on this select into statement below: ``` @MaxAPDRefundAmount money = 13.00 ... select pkd.*, pd.ProviderReference, per.FirstName, per.Surname, @MaxAPDRefundAmount [MaxAPDRefundAmount],commission.Type [Commission] into #StagedData from CTE_PackageData ...
The documentation of the `CREATE TABLE` statement is pretty straightforward. No. Clearly, you cannot use `pkd.*` in a `create table` statement. What you can do is run your old `SELECT INTO` statement as a straight SELECT (remove the `INTO #stagedata`) part, and look at the columns that get returned by the SELECT. Th...
"Do I include all the fields in the select statement into the create statement?" Well, that depends, if you need them, than yes, if not than no. It's impossible for us to say whether you need them... If you're running this exact query as `insert`, than yes. As for the create statement, you can run the query you have, ...
How to create a table with multiple columns
[ "", "sql", "sql-server", "" ]
I want to insert `table1.id` into `table2.t1col` only if `table1.id` doesn't exist in `table2.t1col`, yet. I think I have to use : ``` insert into table2 name (t1col) value (select id from table1) ``` but I want to add only if that `id` doesn't exist in `table2` already.
A unique/index constraint guarantees the uniqueness of values. So, it is recommended. Unfortunately, though, a constraint violation causes the entire `insert` to fail. So, you can do: ``` insert into table2(t1col) select id from table1 t1 where not exists (select 1 from table2 t2 where t2.t1col = t1.id);...
You can use a Unique Index for preventing duplicated rows. But if you want to insert rows filtering it to not insert duplicated rows, you can do this. ``` INSERT INTO table2 (idcol) SELECT id FROM table1 EXCEPT SELECT idcol FROM table2; ```
INSERT into a table from SELECT only if value doesn't exist
[ "", "sql", "postgresql", "sql-insert", "upsert", "" ]
I would like to sort (the result of the sub select) by 3 columns (Priority, ExpectedDate, CreateDate) but for a few row sort should work in different way. It is hard to describe in words so I prepared a picture: [![enter image description here](https://i.stack.imgur.com/Uz4JN.png)](https://i.stack.imgur.com/Uz4JN.pn...
You can do it in two-step process using CTEs: ``` ;WITH InitialRank AS ( SELECT *, ROW_NUMBER() OVER(ORDER BY Priority DESC, ExpectedDate DESC, CreateDate ASC) AS [Rank] FROM Queue ), FinalRank AS ( SELECT t1.ID, t1.ShouldBeAfter, t1.No, t1.C...
Another way to do the same without explicit join: ``` SELECT *, MIN(CASE WHEN ShouldBeAfter = 0 THEN PreRank END) OVER(PARTITION BY CASE WHEN ShouldBeAfter = 0 THEN ID ELSE ShouldBeAfter END) AS [Rank] FROM ( SELECT *, ROW_NUMBER() OVER(ORDER BY Priority DESC, ExpectedDate DESC, CreateDate ASC) AS [PreRank...
SQL ORDER BY with exceptions
[ "", "sql", "sql-server-2008-r2", "sql-order-by", "rank", "" ]
Here is my Query in SQL Server... ``` SELECT hs.NAME Highschooler, hs.grade inGrade1, hs2.NAME likes, hs2.grade inGrade2 FROM highschooler hs JOIN likes l ON hs.id = l.id1 JOIN highschooler hs2 ON hs2.id = l.id2 ``` I get ``` HIGHSCHOOLER INGRADE1 LIKES ...
You probably want to leave data, because Cassandra likes Gabriel and Gabriel likes Cassandra are different actions. So I will suggest the following query: ``` WITH cte AS(SELECT hs.NAME Highschooler , hs.grade inGrade1 , hs2.NAME likes , hs2.grade inGrade2 , ...
You need to remove the duplicates from `likes`. One method is to use `union all` (and this is probably the fastest method if you have an index on `likes(id1, id2)`). You can do the removal before doing the `join`: ``` SELECT hs.NAME as Highschooler, hs.grade as inGrade1, hs2.NAME as likes, hs2.grade as inGrade2 FROM ...
How do I remove duplicate rows based on two Columns? (E.g. A Pair Value Set)
[ "", "sql", "sql-server-2012", "" ]
I have the following SQL Server 2000 query: ``` select distinct m.[Index], m.part as [Part No] from Ctable c, MTable m where m.part *= c.part ``` Is the corresponding SQL Server 2012 query for it this? ``` select distinct m.[Index], m.part as [Part No] from Ctable c right join MTab...
First congrats on getting rid of those old joins, they were not even accurate in SQL server 2000 as they could be misinterpreted as cross joins. That may even be why the distinct was put in (or it could have something to with your data model, without understanding the data you have I can't tell). I believe your conver...
non ANSI standard outer joins were deprecated in 2000 and de-supported in 2005. See <https://msdn.microsoft.com/en-us/library/ms144262(v=sql.90).aspx> Users could still change db\_compat level to get temporary relief for a while but the operators were completely removed in 2012 so you have no alternative. Modify your ...
SQL Server 2000 join query to SQL Server 2012
[ "", "sql", "sql-server", "sql-server-2012", "sql-server-2000", "" ]
I am a beginner in SQL. I have two tables, one is student\_records and the other is a table student\_fees in which the records for students on discounted fees (fee\_type\_code=2) as well as those on regular fees (fee\_type\_code=1) exists. the code for fee type is fee\_type\_code. There is a mistake in system due to wh...
If your goal is to get a list of students that have both fee types then you can use `group by` and `having` instead: ``` select sr.student_id from student_records sr join student_fees sf on sr.student_id = sf.student_id where sf.fee_type_code in (1,2) group by sr.student_id having count(distinct sf.fee_type_code) = 2 ...
As others mentioned earlier, there a few syntactically simpler techniques you could employ to get to this dataset but I wanted to make sure you understood what was wrong with your original query. To explain > "Reference to student\_id is ambiguous..." You have selected `student_id` and `fee_type_code` in your `SELEC...
sql join between two subqueries that are similar
[ "", "sql", "db2", "" ]
I have a table tbl1 How can I split the column values by 10 (number of characters) FROM: ``` Column1 Butuan City Philippines Zamboanga City Philippines Manila City Philippines ``` TO: ``` Column1 Column2 Butuan Cit y Philippines Zamboanga City Philippines Manila Cit y Ph...
You can use the `SUBSTRING()` function: ``` SELECT SUBSTRING(Column1, 1, 10) AS Column1, SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2 FROM yourtable ``` Note that we do not have to worry about using indices in substring which are greater than the length of `Column1`, q.v. the [documentation](https://msdn....
You can use the in-build [SUBSTRING()](https://msdn.microsoft.com/en-IN/library/ms187748.aspx) function of SQL to achieve your expected result. For E.g. ``` IF (LEN(Column1) > 10) BEGIN SELECT SUBSTRING(Column1, 1, 10) AS Column1,SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2 FROM <TABLE> END ```
SQL: Split Column Values into two Columns
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I need to create an output where I got one row per year-month. Assume the dataset is: ``` id | dateStart | dateEnd 1 | 2015-01-01 00:00:00.000 | 2015-03-31 00:00:00.000 2 | 2014-07-01 00:00:00.000 | 2014-08-31 00:00:00.000 ... ``` I need the following output: ``` id | year-month 1 | 2015-01...
Here is a method that uses recursive CTEs: ``` with CTE as ( select id, dateStart as dte, dateEnd from t union all select id, dateadd(month, 1, dte), dateEnd from CTE where dateadd(month, 1, dte) < dateEnd ) select id, dte from CTE; ``` You can convert the final result into an...
Generate tally table(just make sure you get enough rows there). tally will contain values `0,1,2,.....n`. Then you do a join with condition adding thise values as months to `startDate` until it is greater then `endDate`: ``` DECLARE @t TABLE ( id INT , dateStart DATETIME , dateEnd DATETIME ) ...
Split date range to year-month rows on SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have this table here, **Options** ``` ID sType hValue 1 Late 10 2 NSF 20 ``` Now what I want is, a single query to get an output like below: ``` Late NSF 10 20 ``` 2 separate columns with their respective hValues (in a single row). And should have separate column names so that I can...
Add `Max` aggregate on top of your `case` statement ``` SELECT MAX(CASE WHEN sType = 'Late' THEN hValue END) late, MAX(CASE WHEN sType = 'NSF' THEN hValue END) nsf FROM Options WHERE sType IN ('Late', 'NSF') ``` Considering that your `'Late'` or `'NSF'` will not be duplicated
PIVOT is just a shortcut of some other SQL statements. In most case, for PIVOT statement ``` -- Copied from T-SQL 2012 Fundamental. SELECT ... FROM <source_table_or_table_expression> PIVOT(<agg_func>(<aggregation_element>) FOR <spreading_element> IN (<list_of_target_columns>)) AS <result_table_alias>; ``` it can be c...
Is there any alternative to do this except the PIVOT?
[ "", "sql", "" ]
I want to select only one row from a table. This row holds the maximum number in the table. I have tried to use MAX Fun but it didn't work for me. I use two tables to run my query, the first query returns more than one row ``` SELECT Rec_No FROM Records WHERE STATUS = 'Record Replaced'; select Item_No, Quantity fr...
Why does your second query not work... ``` select Item_No, Quantity from Rec_details group by Item_No, Quantity having Quantity=max(Quantity); ``` You are grouping by both `Item_No` and `Quantity` and the `Item_No` appears to be the primary key and contain unique values so each group will on...
One way to get the maximum in Oracle is to use `order by` and `rownum`: ``` select rd.* from (select Item_No, Quantity from Rec_details order by quantity desc ) rd where rownum = 1; ``` The `group by` seems unnecessary. If there are multiple rows with the same quantity, you can also do: ``` select rd....
How can I SELECT the first row with MAX(Column value)?
[ "", "sql", "oracle", "select", "" ]
I have a table with following table Table A ``` Text,id,Cid,CName,Aid,AName Acc.sa is very Acc.pa and Acc.ba is awesome, 1,2,AB,1,CC Acc.aa is awesome and Acc.sas is great,2,3,CC,1,CC Acc.ee is not only great but Acc.sew is best,4,3,FF,1,CC ``` It should fetch all the words associated with Acc so the result should b...
``` with base10 as ( select n from (values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v(n) ), k as ( select d2.n * 100 + d1.n * 10 + d0.n + 1 as n from base10 d0 cross join base10 d1 cross join base10 d2 ) select substring(a.Text, k.n, charindex(' ', a.Text, k.n) - k.n) as Did, Id, Cid, C...
The xml nodes method can be handy for parsing cell values into rows like this. E.g.: ``` select n.value('@s[1]', 'varchar(max)'), id, Cid, CName, Aid, AName from Table_A ta cross apply (select convert(xml, '<x s="' + replace(replace(replace(replace(replace(replace(ta.[Text],'&','&amp;'),'>','&gt;'),'<','&lt;'),'''','&...
Search and Extract a word from rows in SQL
[ "", "sql", "sql-server", "" ]
I have a SQL Server 2014 temp table #SourceTable that looks like this below, where AllTheSamePerDOI is a bit field, defaulted to 0: ``` ID | DOI | Affiliations | SameAffiliationsPerDOI ----+-----+--------------+----------------------- 1 | 1 | Text A | 0 2 | 1 | Text A | 0 3 | 7 | Text CCC ...
I like to approach these problems using updatable CTEs and window functions: ``` with toupdate as ( select st.*, min(Affiliations) over (partition by doi) as mina, max(Affiliations) over (partition by doi) as maxa from #SourceTable st ) update toupdate set SameAffiliation...
``` UPDATE S SET SameAffiliationsPerDOI = 1 FROM #SourceTable S WHERE NOT EXISTS (SELECT 1 FROM #SourceTable S2 WHERE S2.DOI = S.DOI AND S2.Affiliations <> S.Affiliations) ```
SQL - Update a field if all in group are the same
[ "", "sql", "sql-server", "t-sql", "" ]
I have an access database with following structure ``` ID EmployeeID DateTime 1 250 29/11/2015 6:00:00 AM 2 251 29/11/2015 6:01:25 AM 3 252 29/11/2015 7:30:05 AM 4 250 29/11/2015 1:30:45 PM 5 252 ...
Probably not the greatest piece of sql but this will definitely give you what your after ``` SELECT e1.EmployeeID, e1.[DateTime] As StartDateTime, e2.[DateTime] As EndDateTime FROM [EmployeeAccess] e1 INNER JOIN [EmployeeAccess] e2 ON e1.Employeeid = e2.employeeid and ...
If you have only one entry and exit time per day per employee, you can just group by the date which will sort correctly as well: ``` Select EmployeeID, Min([DateTime]) As DateTime1, Max([DateTime]) As DateTime2 From YourLogTable Group By Fix([DateTime]), EmployeeID ```
How to calculate working time on this table?
[ "", "sql", "ms-access", "" ]
Say I have a simple table in postgres as the following: ``` +--------+--------+----------+ | Car | Pet | Name | +--------+--------+----------+ | BMW | Dog | Sam | | Honda | Cat | Mary | | Toyota | Dog | Sam | | ... | ... | ... | ``` I would like to run a sql query that ...
[SQL Fiddle](http://www.sqlfiddle.com/#!15/ced66/6) ``` SELECT distinct unnest(array['car', 'pet', 'name']) AS col, unnest(array[car, pet, name]) AS vals FROM t order by col ```
It's bad style to put set-returning functions in the `SELECT` list and not allowed in the SQL standard. Postgres supports it for historical reasons, but since `LATERAL` was introduced Postgres 9.3, it's largely obsolete. We can use it here as well: ``` SELECT x.col, x.val FROM tbl, LATERAL (VALUES ('car', car) ...
Return column name and distinct values
[ "", "sql", "postgresql", "distinct", "set-returning-functions", "" ]
Company table structure: ``` (`id`=`1`, `name`=`CompanyName`, `members`=`3,52,134,21`) ``` The numbers in the `members` column are the user id's added to this company. When user with `id = 3 OR 52 OR 134 OR 21` is logged in the row above should be returned with a MySQL query. Is this possible with a query or do I h...
Try: ``` SELECT * FROM tbl_name WHERE FIND_IN_SET('3',members); ``` **Note:** Never store data in comma separated format. If it is not late yet, then make one more table and normalize the structure. By normalizing the structure, it will be easy and fast searching by giving indexing to the column. table name: `compan...
Use [**FIND\_IN\_SET()**](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set) function: Try this: ``` SELECT u.* FROM Company c INNER JOIN company_users u ON FIND_IN_SET(u.id, c.members) WHERE c.id = 1; ```
How to find id in MySQL column array
[ "", "mysql", "sql", "select", "join", "find-in-set", "" ]
This is a simple example of the problem I am facing. I have two tables, Job and Person. A Person can work at 1 or more jobs. I need to return one column of data with the job ids of a particular person, but if the person works at job\_id = 'god', then it should return all the job ids. I am using a framework and this mus...
You need to do a join here and then add a where clause to get what you want. The join look like this ``` SELECT P.PERSON_ID, J.JOB_NAME FROM PERSON P JOIN JOB J ON (P.JOB_ID = J.JOB_ID) OR P.JOB_ID = 'god' ``` This will give you a list of people and their jobs. You could even make this a view. Now just select the pe...
Here is the query: ``` select distinct j.job_id from job j join person p on ((j.job_id = p.job_id and p.job_id <> 'god') or p.job_id = 'god') where p.person_id = 'Thor'; JOB_ID ---------- doc ba god select distinct j.job_id from job j join person p on ((j.job_id = p.job_id and p.job_id <> 'god') or p.job_id = 'god')...
Conditional pure sql query
[ "", "sql", "oracle", "oracle11g", "" ]
I'm running into an issue with which I can't figure out how to correctly configure a join. I'm using reporting software that utilizes the (+) indicators in the WHERE clause for our Oracle database. I have two tables: CHECK and TRANSACTION. A check can have multiple transactions, but a transaction doesn't necessarily h...
I'm going to explain this by using equivalent "ANSI JOIN" syntax: ### Option 1 ``` SELECT * FROM TXN LEFT JOIN CHK ON TXN.CHK_ID = CHK.CHK_ID WHERE TXN.CURRENT = 'Y' AND CHK.CURRENT = 'Y' ``` ### Option 2 ``` SELECT * FROM TXN LEFT JOIN CHK ON TXN.CHK_ID = CHK.CHK_ID AND CHK.CURRENT = 'Y' WHERE TXN.CURRENT...
.The `(+)` operator tells Oracle that a predicate is part of an outer join rather than a filter predicate that can be applied after the join. Using the SQL 99 outer join syntax, the first query is equivalent to ``` SELECT * FROM txn left outer join chk on( txn.chk_id = chk.chk_id ) WHERE txn.curren...
Oracle (+) outer join and constant values
[ "", "sql", "oracle", "left-join", "" ]
Hello guys I can not figure out how to write query which would return results where which provider ids are assigned to all operator ids. ``` operatorid-providerid 1 [1] - [3] 2 [2] - [1] 3 [3] - [2] 4 [1] - [3] 5 [2] - [2] 6 [3] - [1] 7 [1] - [2] 8 [2] - [3]...
``` with cte1 as ( select distinct(operatorid) from table ) , cte2 as ( select providerid from table join cte1 on cte1.operatorid = table.operatorid group by providerid having count(distinct(table.operatorid)) = ( select count(*) from cte1 ) ) select table.* from table join ct...
``` select table.* from table where table.providerID in ( select table.providerID from table group by table.providerID having count(distinct table.operatorID) = (select count(distinct table.operatorID) from table) ) ```
SQL get results where column values have same value in other column
[ "", "sql", "" ]
RDMS: MySQL I'm designing a private messaging thread system and have the following schema laid out for the messaging system (simplified). I need to select every conversation that an account with a known ID (we'll say '1') is in, the last message that was sent in the conversation, and the username of the other account ...
First, you don't have any text fields in any of the tables in your pictured schema - so I don't know where you're storing the actual message content or how to retrieve it. That said, this query should work for you and you can just add the field that you need. This will get you the username, the last message received, ...
I have tested this, but maybe this will get you in the right direction. ``` Select m.* from account a inner join account_has_conversation ahc on (a.account_id = account_id) inner join messages m on (ahc.conversation_id = m.conversation_id) where a.account_id = 1 ``` I would add: * Your conversation table doesn't ...
SQL - How would I select data involving multiple tables?
[ "", "mysql", "sql", "" ]
I have T-SQL Table below. ``` ID Cost MaxCost ------------------------------- 2 200 300 3 400 1000 6 20 100 ``` The above table must have 10 rows with IDs 1 to 10. So its missing 7 rows. How do i insert missing rows with proper ID. The cost & maxcost for missing rows will be zero. Do i...
No need for temp table, simple tally derived table and `LEFT OUTER JOIN` are sufficient: ``` CREATE TABLE #tab(ID INT, Cost INT, MaxCost INT); INSERT INTO #tab(ID, Cost, MaxCost) VALUES (2, 200,300),(3, 400, 1000) ,(6, 20, 100); DECLARE @range_start INT = 1 ,@range_end INT = 10; ;WITH tally AS ( SELECT TOP...
Since your number of rows is low you could just define the data explicitly... ``` CREATE TABLE Data(ID INT, Cost INT, MaxCost INT); INSERT INTO Data(ID, Cost, MaxCost) VALUES(2, 200, 300); INSERT INTO Data(ID, Cost, MaxCost) VALUES(3, 400, 1000); INSERT INTO Data(ID, Cost, MaxCost) VALUES(6, 20, 100); ``` and the qu...
TSQL: How do i detect and insert missing records
[ "", "sql", "sql-server", "t-sql", "" ]
I am using SQL Server 2008 and want to convert table data into json format. Can I convert it directly through firing query?
Built in support for formatting query results is added in SQL Server 2016 and it will be available in Azure Database. In older versions you would need to use CLR or some heavy TSQL like: * [Producing JSON Documents from SQL Server queries via TSQL](https://www.simple-talk.com/sql/t-sql-programming/producing-json-docum...
I have created a stored procedure that can take your table and output JSON. You can find it at * [GitHub - SQLTableOrViewToJSON](https://github.com/ahliana/SQLTableOrViewToJSON) Once you run the stored procedure, you can output your table by making a call like the following: ``` EXEC SQLTableOrViewToJSON 'MyTable', ...
How to convert data to json format in SQL Server 2008?
[ "", "sql", "json", "sql-server", "sql-server-2008", "" ]
I'm strugling with what on the first sight appeared to be simple SQL query :) So I have following table which has three columns: PlayerId, Gender, Result (all of type integer). What I'm trying to do, is to select distinct players of gender 2 (male) with number of each results. There are about 50 possible results, so ...
If there are 50 results and you want them in columns, then you are talking about a pivot. I tend to do these with conditional aggregation: ``` select player, sum(case when result = 0 then 1 else 0 end) as result_00, sum(case when result = 1 then 1 else 0 end) as result_01, . . . sum(case wh...
try ``` select player, result, count(*) from your_table where Gender = 2 group by player, result; ```
Selecting count by row combinations
[ "", "sql", "sql-server", "database", "" ]
I need to select the last register for each `budget_id`, which is a foreign key. For example, if my table is: ``` id | budget_id | comment 1 | 8 | Test 1 2 | 8 | Test 2 3 | 5 | Test 1 4 | 5 | Test 2 ``` I need to retrieve like this: ``` id | budget_id | comment 4 | 5 | Test 2 2 | 8 | Test 2 ``` But it is alw...
I think the query is this ``` select id, budget_id,[comment] from note where id in (select max(id) from note group by budget_id) order by id desc ``` In your question , I only see that you want get the max id for every budget\_id , if your purpose is not this ,please give more sample or describe clearly!
You must select max on id and comment then group by budget\_id. SELECT max(id) id, max(comment) as comment, budget\_id from table group by budget\_id order by max(id)
Select last register per group by
[ "", "mysql", "sql", "symfony", "" ]
I am trying to get two columns, `frequency` and `frequency - min(frequency)` but all I see is zero for the second column. What could possibly be wrong? ``` SELECT frequency, frequency - min(frequency) FROM words GROUP BY id ORDER BY frequency; ``` [![enter image description here](https://i.stack.imgur.com...
Your query groups by the unique value of frequency. In each such group, the minimal frequency is just the frequency itself, so you always get `0` when subtracting the two. Instead, you could use the windowing version of `min`: ``` SELECT frequency, frequency - MIN(frequency) OVER() AS diff FROM words ORDER BY fr...
Add a sub-query that returns the min frequency value: ``` SELECT frequency, frequency - (select min(frequency) from words) FROM words ORDER BY frequency; ``` **Edit:** Wrap it up in a derived table: ``` SELECT frequency, frequency - minfreq, frequency + minfreq FROM words CROSS JOIN (select min(freq...
SQL min function
[ "", "sql", "postgresql", "select", "min", "" ]
I have a Visual Studio sql project with a table defined like the following: ``` CREATE TABLE [dbo].[Hoerses] ( [HoersId] INT NOT NULL PRIMARY KEY, [DatePurchased] datetime NOT NULL CONSTRAINT [DF_Hoerses_DatePurchased] DEFAULT DATETIMEFROMPARTS(1985,01,01,0,0,0,0) ) ``` When I target a preexisting SQL database ...
The problem was apparently in the use of `DATETIMEFROMPARTS`. If I instead declare the table as ``` CREATE TABLE [dbo].[Hoerses] ( [HoersId] INT NOT NULL PRIMARY KEY, [DatePurchased] datetime NOT NULL CONSTRAINT [DF_Hoerses_DatePurchased] DEFAULT '1985-01-01' ) ``` Then SqlPackage.exe no longer tries to drop &...
Dacpac deployment works by comparing an XML construct of the Database schema with one from your VS project. Sometimes this process is confused by syntactic niceties resulting in repeating changes such as you describe. My recommendation is that you go to a deployed database, script out the troublesome object and paste t...
How can I prevent SqlPackage.exe from dropping and re-creating constraints when deploying a dacpac?
[ "", "sql", "sql-server", "sqlpackage", "" ]
In database systems, should every table have a primary key? For example I have a table `table1(foreignkey1,foreignkey2,attribute)` like `this.table1` does not have a primary key. Should I define a primary key for this table like `table1id`?
This is a subjective question, so I hope you don't mind me answering with some opinion :) In the vast majority of tables I've made – I'm talking 95%+ – I've added a primary key, and been glad I did. This is either the most critical unique field in my table (think "social security number") or, more often than not, just...
No, it is not required for every table to have a primary key. Whether or not a table should have a primary key is based on requirements of your database. Even though this is allowed it is bad practice because it allows for one to add duplicate rows further preventing the unique identification of rows. Which contradicts...
Is a primary key necessary?
[ "", "mysql", "sql", "" ]
I am asking you how can I mimic this logic in SQL: ``` SELECT var1, var2 FROM table1,WHERE var1 = COUNT(table1.status == 1) AND var2 = COUNT(table2.status == 2) ``` I want to store in `var1` the number of entries that have `status = 1` and in `var2` the number of entries which have `status = 2` in a single `SELECT`.
You can use `COUNT` combined with `CASE`: ``` SELECT COUNT(CASE WHEN t1.Status = 1 THEN 1 END) AS var1, COUNT(CASE WHEN t1.Status = 2 THEN 1 END) AS var2 FROM table1 t1; ``` Alternatively you can use `SUM`: ``` SELECT SUM(t1.status = 1) AS var1, SUM(t1.status = 2) AS var2 FROM table1 t1; ```
If your table is large and has an index on the `status` column, you need to be able to use an index to get fast exection (two index lookups are faster than one table scan), and that requires to filter the rows with WHERE. If you can handle the result as two rows, use a [compound query](http://www.sqlite.org/lang_selec...
SELECT query for two variables in the same table
[ "", "sql", "database", "sqlite", "" ]
I have a table for recording license usage. Each license usage needs to be associated with a user and a host machine. The table definition looks like this. ``` create table if not exists per_user_fact ( per_user_fact_id int unsigned not null auto_increment, time_of_day char(16) ...
I am a big fan of using surrogate primary keys, even in this case. The cost of the additional join is negligible when you are joining to a clustered primary key. In addition, assuming that `username` and `hostname` are (together) longer than four or so characters, the surrogate key saves space. In fact, you might find...
Given the situation explained in the question, i would second the use of a Surrogate key. while a natural PK will give you some advantage on the indexing front, for all practical purposes, the use of surrogates will offer more advantages. Surrogates keep your tables slimmer, give you auditing possibilities etc.
Lookup Table -- Natural or Surrogate key as primary key?
[ "", "sql", "join", "lookup", "surrogate-key", "natural-key", "" ]
Below is my theater table: ``` create table theater ( srno integer, seatno integer, available boolean ); insert into theater values (1, 100,true), (2, 200,true), (3, 300,true), (4, 400,false), (5, 500,true), (6, 600,true), (7, 700,true), (8, 800,true); ``` I want a sql which should take input as 'n' and r...
thanks guys, but i have done achieved it like below, ``` select srno, seatno from ( select *, count(0) over (order by grp) grp1 from ( select t1.*, sum(group_flag) over (order by srno) as grp from ( select *, case when lag(available) over (order by srno) = available t...
In *SQL-Server* you can do It in following: ``` DECLARE @num INT = 4 ;WITH cte AS ( SELECT *,COUNT(1) OVER(PARTITION BY cnt) pt FROM ( SELECT tt.* ,(SELECT COUNT(srno) FROM theater t WHERE available <> 'true' and srno < tt.srno) AS cnt FROM theater tt WHERE available = 'true' ) t1 ) SELECT TOP (...
sql : get consecutive group 'n' rows (could be inbetween)
[ "", "sql", "postgresql-9.3", "gaps-and-islands", "" ]
How can I select specific number of date (let it be third) for all CustomerID in a row for example I have DB looks like ``` +---------+------------+------------+------------+-----------+ | OrderID | CustomerID | EmployeeID | OrderDate | ShipperID | +---------+------------+------------+------------+-----------+ | 10...
``` SELECT CustomerIds.CustomerID ,(SELECT OrderDate FROM Table1 WHERE Table1.CustomerID = CustomerIds.CustomerID ORDER BY OrderDate ASC LIMIT 1 OFFSET 2) AS OrderDate FROM (SELECT CustomerID FROM Table1 GROUP BY CustomerID HAVING COUNT(*) >= 3) AS CustomerIds; ``` [SQLFiddle](http://sqlfiddle.com/...
Try this, ``` select customerid , orderdate from table where GROUP BY customerid ```
select n-th row of certain key SQL
[ "", "mysql", "sql", "database", "" ]
I have a string that looks like: `'10,244,566'` How do I get the `2nd` item? for the above string the item is `244`. The string always looks like `'x,y,z'`. I don't see anything helpful in the manual <http://www.postgresql.org/docs/9.1/static/functions-string.html#FUNCTIONS-STRING-OTHER> **EDIT:** The string is a t...
Looks like a job for [`split_part`](http://www.postgresql.org/docs/9.1/static/functions-string.html#FUNCTIONS-STRING-OTHER) ([sql fiddle](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/5040/0)): ``` select split_part('10,244,566', ',', 2); ```
Splitting strings contained in the database isn't really something that databases were designed for. There's different options here: 1. restructure your data to make strings like `10,244,566` 1. three columns, if it's always three values, or 2. a n-to-m mapping with a second table 2. program the splitting in wh...
How to get an item from string in postgresql?
[ "", "sql", "postgresql", "" ]
i got 3 Tables ``` Player: player_id, player_name Date: date_id, date_value PlayerOnDate: pod_id, player_id, date_id ``` how can i inser something like ``` INSERT INTO `playerondate`(`player_on_date_id`, `player_id`, `date_date_id`) VALUES ( NULL, SELECT player_id WEHRE player_name LIKE 'aName', SELECT ...
There is a specific SQL statement for that INSERT INTO ... SELECT ``` INSERT INTO `playerondate`(`player_on_date_id`, `player_id`, `date_date_id`) SELECT NULL, player_id, date_id FROM playerondate WHERE player_name = 'aName' AND date_value LIKE '12122015' ```
Just add a FROM ``` SELECT player_id FROM Player WHERE player_name = 'aName', SELECT date_id FROM `Date` WHERE date_value LIKE '12122015' ```
mysql: Insert with values from another table
[ "", "mysql", "sql", "insert", "dml", "" ]
**Table1:** id | car1 | car2 | car3 | car4 ``` **Table2:** id | windows | doors | engines ``` I have this sql code: ``` sum(car1) + sum(car2) + sum(car3) + sum(car4) as 'tot_cars', sum('doors') as 'tot_doors' 'tot_doors' - 'tot_cars' as 'door_rest' ``` I've tried this also and not working: ``` sum(car1) + sum(car2...
Do not use single quotes for column aliases. The value of: ``` sum('doors') ``` is 0, because it is summing the string `'doors'`. And, MySQL converts strings to integers based on leading digits -- which results in 0 in this case. Only escape names that need to be escaped, to avoid extra typing and make your queries m...
Aliases are not available on the SELECT clause, so you have to repeat the sum: ``` select sum(car1) + sum(car2) + sum(car3) + sum(car4) as tot_cars, sum(doors) as tot_doors, sum(doors) - sum(car1) - sum(car2) - sum(car3) - sum(car4) as door_rest ``` also you can just use one sum function for each calculated fie...
Simple Sum and Subtract Syntax Error
[ "", "mysql", "sql", "codeigniter", "" ]
I'm working in a fault-reporting Oracle database, trying to get fault information out of it. The main table I'm querying is Incident, which includes incident information. Each record in Incident may have any number of records in the WorkOrder table (or none) and each record in WorkOrder may have any number of records ...
I would do this with `row_number` function: [SQLFiddle](http://sqlfiddle.com/#!4/1ec4f/1) ``` select ticketid, case when worklogid is not null then reportdate end d1, mxronsite d2 from ( select i.ticketid, wo.reportdate, wl.mxronsite, wo.wonum, wl.worklogid, row_number() over (partition by i.ticketid...
I may not have the details right on what you're trying to do... if you have some sample input and desired output, that would be a big help. That said, I think an analytic function would help a lot, not only in getting the output but in organizing the code. Here is an example of how the `max` analytic function in a sub...
ORA-00904 "invalid identifier" but identifier exists in query
[ "", "sql", "oracle", "identifier", "" ]
Let's say I have a database with N tables (30-50) with different data. All tables have column "CreatedDate" So, I want to select last 100 records from database based on this date for all tables for log/audit purposes. One way is to do `union all` on all tables manually. Or use stored procedure along with `sys.tables`...
I guess thos top 100 rowas may be from just one of the tables hence the TOP 100 for each table. But with below, I believe you just need to write the function "FunctionToGetAllColumnsForTableIntoOneBigOne()" whcich you should be able to do with the other link I supplied..... ``` DECLARE @dt DateTime = GetDate(); DECLAR...
You can use dynamic SQL ... hope this helps ``` DECLARE @sql NVARCHAR(MAX) = N''; SELECT @sql += N' SELECT TOP (100) * FROM ' + QUOTENAME(SCHEMA_NAME([schema_id])) + '.' + QUOTENAME(name) + ' ORDER BY CreatedDate DESC'';' FROM sys.tables AS t; PRINT @sql; EXEC sp_executesql @sql; ``` OR Wrap around ...
How to display last 100 rows from all tables across database
[ "", "sql", "sql-server", "" ]
## Desired result : Have an accent sensitive primary key in MySQL. I have a table of unique words, so I use the word itself as a primary key (by the way if someone can give me an advice about it, I have no idea if it's a good design/practice or not). I need that field to be accent (and why not case) sensitive, becau...
**Collations**. You have two choices, not three: `utf8_bin` treats all of these as *different*: `demandé` and `demande` and `Demandé`. `utf8_..._ci` (typically `utf8_general_ci` or `utf8_unicode_ci`) treats all of these as the *same*: `demandé` and `demande` and `Demandé`. If you want only case sensitivity (`demandé...
May be you need this \_ci in a collation name=case insensitive If your searches on that field are always going to be case-sensitive, then declare the collation of the field as utf8\_bin... that'll compare for equality the utf8-encoded bytes. `col_name varchar(10) collate utf8_bin` If searches are normally case-inse...
Use accent sensitive primary key in MySQL
[ "", "mysql", "sql", "encoding", "primary-key", "diacritics", "" ]
I have 3 tables like this: ``` CREATE table materials (id serial primary key not null, name varchar(50) not null, unit varchar(10) not null default 'шт', price decimal(12, 2) not null check (price>0)); CREATE table warehouses (id serial primary key not null, lastname varchar(25) not null); CREATE table materia...
You can solve this with subqueries like this: First case, count > 100 at each warehouse ``` SELECT * FROM materials WHERE id IN ( SELECT m.id FROM materials_in_warehouses AS mw INNER JOIN materials AS m ON (m.id = mw.id_materials) WHERE m.price > 200 AND mw.count > 100 ...
You will need to firstly JOIN the tables and establish the relationships. ``` SELECT w.lastname , m.name , m.price , miw.count FROM materials m INNER JOIN materials_in_warehouses miw ON m.id = miw.id_materials INNER JOIN warehouses w ON w.id = miw.id_warehouses ``` From there, you can add where clauses t...
Postgresql no ideas to select query
[ "", "sql", "postgresql", "select", "" ]
I have two tables: one is foreign reference table lets say ***table a*** and other one is the data table lets say ***table b***. Now, when I need to change the data in ***table b***, but I get restricted by ***table a***. How can I change "rid" in both tables without getting this message? > "ERROR: insert or update on...
In Postgres you can use a writeable CTE to update both tables in a single statement. Assuming this table setup: ``` create table a (rid integer primary key, ride text, qunta integer); create table b (kid integer primary key, rid integer references a, date date); ``` The CTE would be: ``` with new_a as ( update a ...
you can not update/delete primary key in table B, because the primary key is used in table A. you can delete primary key in table B, IF >> 1. you must delete the row in table A which is used primary key table B. 2. you can delete the row in table B
How to update rows of two tables that have foreign key restrictions
[ "", "sql", "postgresql", "" ]