Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Suppose I have a Product table, and a
```
id product
1 Apple
2 Bag
3 Cat
4 Ducati
```
and a Cart table
```
id user_id product_id
1 1 2
2 1 3
3 2 1
4 3 1
```
So, I want to look at a particular user and see what he/she does NOT have in their Cart.
In ot... | Perform a left join from product to all products purchased by user1, which can be retrieved with a subselect in the join. This will cause all product id's that are not in user1's care to have null product ids. The where clause will select all null product id's meaning they will not have been in a users cart, essentiall... | ```
Select
*
From Product p
Where p.id Not In
(
Select c.product_id
From Cart c
Where User ID = ____
)
``` | Matching items in one table that don't match in a subset of a second table | [
"",
"mysql",
"sql",
""
] |
I have a SSRS report that do not display data in preview mode. However, when I run the same query in SQL Server 2008 R2 I can retrieve the results
What could cause this?
I also used Set FMTOnly to off because I use temptables. | if you use "SQL Server Business Intelligence Development Studio" not "Report Builder" then on reporting services (where is you table):
1. click View -> Properties Window (or just press F4)
2. select the tablix
3. on properties window find "General" and in the "DataSetName" choose your "Dataset"
4. On tablix fields set... | **The Best solutio**
**Select the entire row and change the font to arial or any other font other than segoe UI**
1. default font
[default font](https://i.stack.imgur.com/WbRRD.png)
2. no display in preview
[no display in preview](https://i.stack.imgur.com/8diWq.png)
3. changed font first row
[changed font fi... | SSRS not displaying data but displays data when query runned in tsql | [
"",
"sql",
"t-sql",
"reporting-services",
"sql-server-2008-r2",
"bids",
""
] |
According to [MySQL documentation](http://dev.mysql.com/doc/refman/5.0/en/if.html) this would run on mysql.version > 5. But I get:
> #1064 - You have an error in your SQL syntax; check the manual that
> corresponds to your MySQL server version for the right syntax to use
> near 'IF
Code:
```
IF SELECT MAX(`amount`) ... | The cause of the error is the fact that you can't use `IF` statement in plain query it can be used **only** in a context of a stored routine (procedure, function, trigger, event).
Your first piece of code will work successfully in a stored procedure *with shlight changes*
```
DELIMITER $$
CREATE PROCEDURE insert500()... | That should be:
```
IF SELECT MAX(`amount`) FROM transactions WHERE amount < 500
THEN
INSERT INTO transactions (amount) VALUES (500)
END IF
``` | INSERT '100' into table IF '100' is the highest value gives error | [
"",
"mysql",
"sql",
"if-statement",
""
] |
I have to select data from a table using column values that contain texts with numbers, like this:
```
"SELECT Title, Category from BookList where CategoryField BETWEEN '"
+ blockCodeStart + "' AND '" + blockCodeEnd + "'";
blockCodeStart = "A25"
blockCodeEnd = "A39"
```
I understand that and could handle either te... | `foo BETWEEN bar AND baz` is just a handy shortcut for `bar <= foo AND foo <= baz`. You can NOT expect to get "normal" results if you're comparing apples and oranges - since you're comparing STRINGS, you'll get string results. You can NOT expect the DB to able to be figure out that `A25` is greater than `A9`. It's not ... | If all values in field Category has same format 'LETTER' + 'DIGITS' then you can create function that compare categories.
In this example I created and use schema `test`.
```
drop table if exists test.aaa;
drop function if exists test.natural_compare(s1 character varying, s2 character varying);
create or replace fun... | BETWEEN operator when range has texts with numbers | [
"",
"sql",
"between",
""
] |
Customer
```
CustomerID Name
4001 John Bob
4002 Joey Markle
4003 Johny Brown
4004 Jessie Black
```
Orders
```
OrderID Customer Status
50001 4001 Paid
50002 4002 Paid
50003 4001 Paid
50004 4003 Paid
50005 4001 Paid
50006 4003 ... | You will have to use a more complex `left join` in order to only count the `Paid` ones:
```
SELECT c.customerid, count(o.orderid) TotalOrders
FROM customer c
LEFT JOIN orders o
ON c.customerid = o.customer AND o.status = 'Paid'
GROUP BY c.customerid
```
Output:
```
| CUSTOMERID | TOTALORDERS |
|------------|--------... | Use a left join
```
Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
left join Orders o
on c.Customer = o.Customer
Group by c.Customer
``` | Count and Joins with Where | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
Let's assume two tables:
TableA holds various data measurements from a variety of stations.
TableB holds metadata, about the columns used in TableA.
TableA has:
```
stationID int not null, pk
entryDate datetime not null, pk
waterTemp float null,
waterLevel float null ...etc
```
TableB has:
```
id int not null, pk, ... | dynamic SQL with PIVOT is the answer. though it is dirty in terms of debugging or say for some new developer to understand the code but it will give you the result you expected.
check the below query.
in this we need to prepare two things dynamically. one is list columns in the result set and second is list of values... | I would design this database like the following:
A table `MEASUREMENT_DATAPOINT` that contains the measured data points. It would have the columns `ID`, `measurement_id`, `value`, `unit`, `name`.
One entry would be `1, 1, 2.4, 'celcius', 'water temperature'`.
A table `MEASUREMENTS` that contains the data of the meas... | Create a view based on column metadata | [
"",
"sql",
"sql-server-2008",
"metadata",
""
] |
I have 3 tables.
I need info from 2 of the tables, while the 3rd table links them.
Can someone give me an example of the joins to use?
for this example, I need insured’s first and last names, the effective date and the expiration date of their policies.
Mortal table
```
SQL> desc mortal
Name
--------------------... | This is still an easy join. Here is one way.
```
select m.first_name, m.last_name, p.effective_date, p.expired_date
from mortal m
inner join policy p
on p.policy_id = i.policy_id
inner join insured i
on i.mortal_id = m.mortal_id
```
Not sure what the problem is. But if the question is just "can you join a... | You simply need to join the tables. The type of join is depended on what you are trying to acheive. Below is a basic example:
```
SELECT a.field, c.field
FROM [Mortal Table] a
JOIN [Insured Table] b ON a.MORTAL_ID=b.MORTAL_ID
JOIN [Policy Table] c on b.POLICY_ID=c.POLICY_ID
*WHERE Clause*
```
Hope this helps. | Join 3 tables, only use data from 2? | [
"",
"sql",
"database",
"oracle11g",
""
] |
My MySQL 5.5 server has set `autocommit=1`.
My stored procedure has several DMLs but without explicit transaction management.
When I issue `call the_procedure()` from MySQL CLI (`autocommit` is still 1), do all the procedure's DMLs run in one transaction?
Or do they run in separate transactions, and causing implicit... | They run in separate transactions if `autocommit=1`. Suppose you define
```
CREATE TABLE test ( id int PRIMARY KEY )//
CREATE PROCEDURE sp_test_trans()
BEGIN
INSERT INTO test (id) VALUES (1);
INSERT INTO test (id) VALUES (2);
ROLLBACK;
END//
```
If you run this procedure with `autocommit=0`, the `ROLLBACK` wil... | [This](https://www.oreilly.com/library/view/mysql-stored-procedure/0596100892/re31.html) is surprising to me but:
> Although MySQL will automatically initiate a transaction on your
> behalf when you issue DML statements, you should issue an explicit
> START TRANSACTION statement in your program to mark the beginning o... | Do DMLs in a stored procedure run in a single transaction? | [
"",
"mysql",
"sql",
"database",
"stored-procedures",
""
] |
I have SQL Server database and I want to change the identity column because it started
with a big number `10010` and it's related with another table, now I have 200 records and I want to fix this issue before the records increases.
What's the best way to change or reset this column? | > **You can not update identity column.**
>
> SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.
Although there are some alternatives to achieve a similar kind of requirement.
* **When Identity column value needs to be updated for new records**
... | If got your question right you want to do something like
```
update table
set identity_column_name = some value
```
Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some `foreign key` associated on it.
But here are steps to do it, Please take a `back-up` of table
Step 1-... | How to update Identity Column in SQL Server? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008",
""
] |
In MySQL, I want to fire a trigger *after the update* of specific columns.
I know how to do it in Oracle and DB2:
```
CREATE TRIGGER myTrigger
AFTER UPDATE of myColumn1,myColumn2 ... ON myTable
FOR EACH ROW
BEGIN
....
END
```
How to do that with MySQL? | You can't trigger on a particular column update in SQL. It is applied on a row.
You can put your condition for columm in your trigger with an `IF` statement, as below:
```
DELIMITER //
CREATE TRIGGER myTrigger AFTER UPDATE ON myTable
FOR EACH ROW
BEGIN
IF !(NEW.column1 <=> OLD.column1) THEN
--type your state... | You can't specify only to fire on specific column changes. But for a record change on a table you can do
```
delimiter |
CREATE TRIGGER myTrigger AFTER UPDATE ON myTable
FOR EACH ROW
BEGIN
...
END
|
delimiter ;
```
In your trigger you can refer to old and new content of a column like this
```
if NEW.column1 <> ... | Fire a trigger after the update of specific columns in MySQL | [
"",
"mysql",
"sql",
"triggers",
""
] |
I have a query where the individual selects are pulling the most recent result from the table. So I'm having the select order by id desc, so the most recent is top, then using a rownum to just show the top number. Each select is a different place that I want the most recent result.
However, the issue I'm running into ... | By putting `where .. and rownum = 1` condition before `order by` clause you wont produce desired result because the result set will be ordered after the `where` clause applies, thus ordering only one row in the result set which can be whatever first row is returned by the query.
Moreover, putting `order by` clause rig... | Try this
```
select 'MUHC' as org,
aa,
messagetime
from buffer_messages bm
where aa = 'place1'
and id= (Select max(id) from buffer_messages where aa = 'place1' )
union all
select 'MUHC' as org,
aa,
messagetime
from buffer_messages
where aa = 'place2'
and id= (Select max(id) from buffer_messages ... | Oracle - order by in subquery of union all | [
"",
"sql",
"oracle",
""
] |
The problem: I have a MySQL database table which holds article numbers and 2 parameters related to the article:
```
article_no | parameter1 | parameter2
1111111 | false | false
2111111 | true | true
1222222 | false | false
2222222 | false | false
```
Articles are represented by 2 ... | You can achieve that with one `UPDATE` query, like:
```
UPDATE
t AS l
LEFT JOIN t AS r
ON SUBSTR(l.article_no, 2)=SUBSTR(r.article_no, 2)
AND l.article_no LIKE '1%'
AND r.article_no LIKE '2%'
SET
l.parameter2='true'
WHERE
r.parameter1='true'
``` | From my understanding, you want to update the parameter 1 and 2 with following condition:if prefix is '1' then 'true' and if the prefix is '2' then false. Here's the query:
```
UPDATE article SET parameter1 = 'true', parameter2 = 'true' WHERE article_no LIKE '1%';
UPDATE article SET parameter1 = 'false', parameter2 =... | sql statement to change somehow related rows | [
"",
"mysql",
"sql",
""
] |
I have a MySql Table with the following schema.
```
table_products - "product_id", product_name, product_description, product_image_path, brand_id
table_product_varient - "product_id", "varient_id", product_mrp, product_sellprice, product_imageurl
table_varients - "varient_id", varient_name
table_product_categories - ... | the query below would be a start, or something similar
```
SELECT
*
FROM
table_products P
INNER JOIN
table_product_categories PC
ON
PC.product_id = P.product_id
INNER JOIN
table_product_varients PV
ON
P.product_id = PV.product_id
INNER JOIN
table_varients V
ON
V.varient_id = PV.varien... | You can use the EXPLAIN command to see whats happening in the server. Then you can optimize the request by creating indexes.
Some links:
* [Some slides about tuning](http://de.slideshare.net/manikandakumar/mysql-query-and-index-tuning)
* [MYSQL manual: 8.2.1. Optimizing SELECT Statements](http://dev.mysql.com/doc/ref... | Is there any way to optimize this MYSQL query | [
"",
"mysql",
"sql",
"query-optimization",
""
] |
Here is a schema about battleships and the battles they fought in:
```
Ships(name, yearLaunched, country, numGuns, gunSize, displacement)
Battles(ship, battleName, result)
```
A typical Ships tuple would be:
```
('New Jersey', 1943, 'USA', 9, 16, 46000)
```
which means that the battleship New Jersey was launched... | Well, `name = ship` is the problem. `name` could be from `a` or `b`, and `ship` from `b1` or `b2`
you could do something like that :
```
select distinct s1.country, s2.country
from ships s1
inner join Battles b1 on b.ship = s1.name
inner join Battles b2 on b2.ship <> s1.name and b2.battleName = b1.battleName
inner jo... | Could you try a nested query getting a table of winners and losers and then joining them on the battle name?
```
SELECT
WINNER.country as Country1
,LOSER.country as Country2
FROM
(
SELECT DISTINCT country, battleName
FROM Battles
INNER JOIN Ships ON Battles.ship = Ships.name
WHERE Battles.Result = 1
) AS WIN... | battles, ships sql query | [
"",
"sql",
"countries",
""
] |
I am going through some kind of problem. Here is the table schema.
I have two tables job,application.
```
Application: aid,aname,stime,jname
Job:jid,jname,aid,start,end
Application table:
aid aname stime
A ABC 23-SEP-13
B DEF 24-SEP-13
Job table:
jid jname aid start ... | Try like this,
```
SELECT a.aname,
A.stime,
j.jname,
floor(end - start) DAYS ,
MOD(FLOOR ((end - start) * 24), 24) HOURS ,
MOD (FLOOR ((end - start) * 24 * 60), 60) MINUTES ,
MOD (FLOOR ((end - start) * 24 * 60 * 60), 60) SECS
FROM application a,
... | Try this one using [**TIMESTAMPDIFF**](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff) specify the format like want to get difference in months ,days,minutes or seconds
```
SELECT a.aname ,a.stime , j.jname,
TIMESTAMPDIFF(DAY,j.`end`,j.`start`) AS 'end-start',
TIMESTAMPDI... | Combining different tables and extracting data on conditions | [
"",
"sql",
"oracle",
""
] |
I'm having a hard time figuring out how to **merge together two columns** with sql (I'm new at it). It should be really simple but I simply can't find a way to do it. I have two results from **two different selects statements**, and they both have the **same number of rows**, but **different columns**. I just want to "... | ```
SELECT [t].*,
[d].[Description] AS [Name],
[d2].[Description] AS [Description]
FROM [TrainerClass] AS [t] join [DescriptionTranslation] AS [d] on [t].[Code] = [d].[Code]
join [DescriptionTranslation] AS [d2] on [t].[Code] = [d2].[Code]
WHERE [d].[TableName] = 'TrainerClass' AND
[d].[... | I you have any common ID in your tables, you can use join as stated in answers, otherwise you can use union statement | Merging two or more columns from different SQL queries | [
"",
"sql",
"select",
"merge",
""
] |
So I am trying to build a query that will show me which users have the most points, for each type of activity. You can see the table strucutre below. Each activity has an **activity\_typeid** and each of those carries a certain **activity\_weight**.
In the example below, Bob has scored 50 points for calls and 100 poin... | What you need is equivalent of analytic function `DENSE_RANK()`. One way to do it in if you need top performers for each activity
```
SELECT a.activity_typeid, GROUP_CONCAT(a.userid) userid
FROM
(
SELECT activity_typeid, userid, SUM(activity_weight) activity_weight
FROM table1
-- WHERE ...
GROUP BY userid... | You must use the `GROUP BY` statement to calculate the sum for each user and each activity typeid. Try something like this:
```
SELECT userid, activity_typeid, SUM(activity_weight)
FROM table
GROUP BY userid, activity_typeid
```
Then use this as a subquery to determine the top performer for each activity\_typeid. | using SUM and DISTINCT in the same query | [
"",
"mysql",
"sql",
""
] |
I want to write a select statement output that, among other things, has both a lowest\_bid and highest\_bid column. I know how to do that bit, but want I also want is to show the user (user\_firstname and user\_lastname combined into their own column) as lowest\_bidder and highest\_bidder. What I have so far is:
```
s... | This seems like good use of window functions. I've assumed a column `vb_bids.bid_user_id`. If there's no link between a bid and a user, you can't answer this question
```
With x as (
Select
b.bid_item_id,
count(*) over (partition by b.bid_item_id) as number_of_bids,
row_number() over (
... | In order to get the users, I broke out the aggregates into their own tables, joined them by the `item_id` and filtered them by a derived value that is either the min or max of `bid_amount`. I could have joined to `vb_bids` for a third time, and kept the aggregate functions, but that would've been redundant.
This will ... | Select statement to show the corresponding user with the lowest/highest amount? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
In MS SQL Server I have a filed of type double that is called `ID`, and that stores ID numbers, surprisingly enough.
Anyway, I want to be able to search ID numberss like text - say I want all ID's that starts with 021 or that ends with 04 - to do so I need to convert the double the string.
My problem is that ID number... | If your ID's are stored as numbers, then there will not be prefixed zeros, so finding all records that starts with '021' really means finding those that starts with '21'
```
SELECT * FROM MyTable
WHERE CAST(Id AS VARCHAR) LIKE '21%'
``` | `SELECT * FROM tablename
WHERE SUBSTRING(CAST(id AS VARCHAR), 0, 9) = '123456789'` | MS SQL Server: cast double to string and compare text | [
"",
"sql",
"sql-server",
"casting",
""
] |
I am trying to store the results of an SQL query into a variable.The query simply detects the datatype of a column, hence the returned result is a single varchar.
```
SET @SQL =
'declare @@x varchar(max) SET @@x = (select DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE Table_name = ' +char(39)+@TabName+char(... | You dont need a dynamic query to achieve what you want, below query will give the same result as yours.
```
declare @x varchar(max)
declare @tableName varchar(100), @ColumnName varchar(50)
set @tableName = 'Employee'
set @ColumnName = 'ID'
select @x = DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
where
... | All user-defined variables in T-SQL have private local-scope *only*. They cannot be seen by any other execution context, not even nested ones (unlike #temp tables, which *can* be seen by nested scopes). Using "*@@*" to try to trick it into making a global-variable doesn't work.
If you want to execute dynamic SQL and r... | T-SQL: Variable Scope | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
"stored-procedures",
""
] |
I'm working on a small project in which I'll need to select a record from a temporary table based on the actual row number of the record.
How can I select a record based on its row number? | A couple of the other answers touched on the problem, but this might explain. There really isn't an order implied in SQL (set theory). So to refer to the "fifth row" requires you to introduce the concept
```
Select *
From
(
Select
Row_Number() Over (Order By SomeField) As RowNum
, *
From TheTable
)... | Technically SQL Rows do not have "RowNumbers" in their tables. Some implementations (Oracle, I think) provide one of their own, but that's not standard and SQL Server/T-SQL does not. You can add one to the table (sort of) with an IDENTITY column.
Or you can add one (for real) in a query with the ROW\_NUMBER() function... | How to select a row based on its row number? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I've read this article: <http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/> and search for other questions
I have a table that is something like:
```
| table.id | USER.id
----------------------------------------------
| 1 | 101
| 2 | 101
| 3 | ... | You can simplify your query, and use [LEAST](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least) function
```
SELECT USERid, LEAST(7, COUNT(*))
FROM table
GROUP BY USERid
```
from the question in your comment
```
SELECT SUM(countByUser)
FROM
(SELECT LEAST(7, COUNT(*)) as countByUser
... | ```
SELECT userid,
CASE
WHEN COUNT(*) > 7 THEN 7
ELSE COUNT(*)
END AS Qty
FROM tbl
GROUP BY userid
``` | mysql select the first n rows per group | [
"",
"mysql",
"sql",
"group-by",
""
] |
I have a situation where I need to get the differences between two columns.
> Column 1: 01-OCT-13 10:27:15
> Column 2: 01-OCT-13 10:28:00
I need to get the differences between those above two columns. I tried using '-' operator but the output is not in an expected way.
I need output as follows: 00-00-00 00:00:45 | Try this query but it is not tested
```
SELECT extract(DAY
FROM diff) days,
extract(hour
FROM diff) hours,
extract(MINUTE
FROM diff) minutes,
extract(SECOND
FROM diff) seconds,
extract(YEAR
FROM diff) years
FROM
(S... | Try this too,
```
WITH T(DATE1, DATE2) AS
(
SELECT TO_DATE('01-OCT-13 10:27:15', 'DD-MON-YY HH24:MI:SS'),TO_DATE('01-OCT-13 10:28:00', 'DD-MON-YY HH24:MI:SS') FROM DUAL
)
SELECT floor(date2 - date1)
|| ' DAYS '
|| MOD(FLOOR ((date2 - date1) * 24), 24)
|| ' HOURS '
|| MOD (FLOOR ... | Date Time differences calculation in Oracle | [
"",
"sql",
"oracle",
""
] |
I've got 2 databases, let's call them **Database1** and **Database2**, a user with very limited permissions, let's call it **User1**, and a stored procedure in **Database1**, let's call it **Proc1**.
I grant `EXECUTE` permission to **User1** on **Proc1**; `GRANT EXECUTE ON [dbo].[Proc1] TO [User1]` and things worked f... | There seem to be a difference when SQL Server checks the permissions along the permission chain. Specifically:
> SQL Server can be configured to allow ownership chaining between specific databases or across all databases inside a single instance of SQL Server. Cross-database ownership chaining is disabled by default, ... | Late to the party, but I recommend taking a look at signed stored procedures for this scenario. They are much more secure than granting users permissions to multiple databases or turning on database ownership chaining.
> ... To make it possible for a user to run this procedure without
> SELECT permission on testtbl, y... | How GRANT EXECUTE and cross-database reference works in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I have the data in one column.
Ex:
dog
dog
cat
fox
How do I change the value of all dogs to fox and values of all fox to dog at the same time? If I run an UPDATE SET it will change all dogs to fox, then I run the second one it'll turn everything into dogs. | ```
update
table
set
animal = case anmial when 'dog' then 'fox' else 'dog' end
where
animal in ('dog', 'fox')
``` | If you have more than just dogs and foxes you could consider making a conversion table to help you with the update. That way you won't need a case statement.
```
declare @original table
(
pk int identity(1,1),
column1 varchar(max)
)
insert into @original
select 'fox'
union all
select 'dog'
declare @conversi... | How to swap values from two fields at the same time in SQL? | [
"",
"sql",
"sql-server",
""
] |
Let's say I have a table like this (with the `num` column being indexed) :
```
+-----+--------------+
| num | lots of cols |
+-----+--------------+
| 31 | bla 31 |
| 67 | bla 67 |
| 88 | bla 88 |
| 89 | bla 89 |
+-----+--------------+
```
And I want to swap the num of one row whose num is ... | First get the number that you want to swap with:
```
select max(num)
from TheTable
where num < 88
```
Then use that to swap the numbers:
```
update TheTable
set num = (67 + 88) - num
where num in (67, 88)
```
(Note however that this only works as long as the sum of the two numbers are still within the range of the ... | This is based on @Guffa's answer. It simply combines the two queries into one:
```
update TheTable cross join
(select max(num) as num
from TheTable
where num < 88
) other
set num = (other.num + 88) - num
where num in (other.num, 88);
``` | Swap with precedent | [
"",
"mysql",
"sql",
""
] |
How do you run a SQL command in a shell script while setting a variable? I had tried this method and it isn't executing the command, it is thinking the command is just a string.
```
#!/bin/ksh
variable1=`sqlplus -s username/pw@oracle_instance <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
select cou... | ```
#!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
" | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"
``` | You can use a [heredoc](http://en.wikipedia.org/wiki/Here_document). e.g. from a prompt:
```
$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF
```
so `sqlplus` will consume everything up to the `EOF` marker as stdin. | How to run SQL in shell script | [
"",
"sql",
"oracle",
"shell",
"unix",
""
] |
I need to get date range between 1st July till 31st October every year. Based on that I have to update another column.
Date field is datetime. Should be like this below:
```
Select Cash = Case When date between '1st July' and '31st October' Then (Cash * 2) End
From MytTable
```
Note: this range should work for each ... | This is one way:
```
SELECT Cash = CASE WHEN RIGHT(CONVERT(VARCHAR(8),[date],112),4)
BETWEEN '0701' AND '1031' THEN Cash*2
ELSE Cash END --I added this
``` | For your case you could just use the month and make sure it falls between 7 to 10.
This is how your query will be:
```
select Cash = case when month([Date]) in (7, 8, 9, 10) then (Cash * 2) else Cash end
```
or
```
select Cash = case when month([Date]) between 7 and 10 then (Cash * 2) else Cash end
``` | Get date range between dates having only month and day every year | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have below 3 records in my table(**TAG\_DATA**) column(**TAGS**).
```
car,bus,van
bus,car,ship,van
ship
```
I wrote a query to get records which has `car` and `bus` as below.
```
SELECT * FROM TAG_DATA
where TAGS like '%car, bus%'
```
But above query return only below record.
```
car,bus,van
```
But i need to... | Please try:
```
DECLARE @input NVARCHAR(MAX)='car, bus'
SELECT DISTINCT B.*
FROM(
SELECT
LTRIM(Split.a.value('.', 'VARCHAR(100)')) AS CVS
FROM
(
SELECT
CAST ('<M>' + REPLACE(@input, ',', '</M><M>') + '</M>' AS XML) AS CVS
) AS A CROSS APPLY CVS.nodes ('/M') AS Spli... | Here, only records having `car, bus` tags in sequence will be fetched.
For the desired result, below query is beneficial :
```
SELECT * FROM TAG_DATA
where TAGS like '%car, bus%' or TAGS like '%bus, car%'
```
**[SQL FIDDLE](http://sqlfiddle.com/#!3/55ad4f/1)** | Query a table to find records with given text | [
"",
"sql",
"sql-server",
"select",
""
] |
I hope that you can help me on some SQL theory, as I am not 100% sure how this works.
If I have a trigger and I define it as
```
AFTER DELETE ON xxxx
```
I was wondering when exactly this would fire, in terms of transaction management?
So if I delete a record from my table I assume that the trigger will not fire un... | ```
1. You delete a row on TABLE1 no COMMIT;
2. TRIGGER performs an action (This takes place before COMMIT or ROLLBACK for step1, but trigger will not have any commit or rollback in it)
3a. You apply commit - Both step1 and step2 gets completed .
3b. You apply rollback- Both step1 and step2 rolled back.
```
Either you... | The purpose of SQL triggers is to ensure referential consistency. But when they would be exectued in a separate transaction commit, there would be the possibility that they leave data in an inconsistent state.
So the delete trigger is executed the moment you do the delete command. When this happens as a transaction an... | When exactly is an AFTER DELETE trigger fired | [
"",
"sql",
""
] |
I'm trying to select the user who has the MAX microposts count:
```
SELECT "name", count(*) FROM "users"
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
GROUP BY users.id
```
and this returns
```
"Delphia Gleichner";15
"Louvenia Bednar IV";10
"Example User";53
"Guadalupe Volkman";20
"Isabella H... | I'd try with a ORDER BY max DESC LIMIT 1, where maximum is the count(\*) field. Something like:
```
SELECT "name", count(*) maximum FROM "users"
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
GROUP BY users.id
ORDER BY maximum DESC
LIMIT 1
```
I dont' have mysql available now, so I'm doing th... | ```
SELECT x.name, MAX(x.count)
FROM (
SELECT "name", count(*)
FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
GROUP BY users.id
) x
GROUP BY x.name
``` | SQL select MAX(COUNT) | [
"",
"sql",
""
] |
Currently I am using the following query to display the following result.
```
SELECT * FROM RouteToGrowthRecord, GradeMaster,MileStoneMaster
WHERE MemberID = 'ALV01L11034A06' AND
RouteToGrowthRecord.GradeID=GradeMaster.GradeID AND
RouteToGrowthRecord.MileStoneID=MileStoneMaster.MileStoneID
ORDER BY CheckupDate DESC
`... | You can use Union here to merge the results getting from both queries. Use default values for the unmapped additional fields. | ```
SELECT * FROM RouteToGrowthRecord a inner join GradeMaster b inner
join MileStoneMaster c inner join RouteToGrowthRecord_st d on
a.GradeID=b.GradeID AND a.MileStoneID=c.MileStoneID and
d.GradeID=b.GradeID AND d.MileStoneID=c.MileStoneID
WHERE a.MemberID = 'ALV01L11034A06'
ORDER BY Ch... | Sql query to combine result of two tables | [
"",
"mysql",
"sql",
""
] |
NOTE: I checked [Understanding QUOTED\_IDENTIFIER](https://stackoverflow.com/questions/7481441/understanding-quoted-identifier) and it does not answer my question.
I got my DBAs to run an index I made on my Prod servers (they looked it over and approved it).
It sped up my queries just like I wanted. However, I starte... | OK, from an application developer's point of view, here's what these settings do:
## QUOTED\_IDENTIFIER
This setting controls how quotation marks `".."` are interpreted by the SQL compiler. When `QUOTED_IDENTIFIER` is ON then quotes are treated like brackets (`[...]`) and can be used to quote SQL object names like ta... | I find [the documentation](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-quoted-identifier-transact-sql), [blog posts](http://ranjithk.com/2010/01/10/understanding-set-quoted_identifier-onoff/), [Stackoverflow answers](https://stackoverflow.com/questions/7481441/understanding-quoted-identifier) unhelpful i... | ANSI_NULLS and QUOTED_IDENTIFIER killed things. What are they for? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I have a search screen where the user has 5 filters to search on.
I constructed a dynamic query, based on these filter values, and page 10 results at a time.
This is working fine in SQL2012 using `OFFSET` and `FETCH`, but I'm using ***two*** queries to do this.
I want to show the 10 results *and* display the total... | You don't have to run the query twice.
```
SELECT ..., total_count = COUNT(*) OVER()
FROM ...
ORDER BY ...
OFFSET 120 ROWS
FETCH NEXT 10 ROWS ONLY;
```
Based on [the chat](https://chat.stackoverflow.com/rooms/38509/discussion-between-user788312-and-aaron-bertrand), it seems your problem is a little more complex - you... | My solution is similar to "rs. answer"
```
DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 2
SET @RowspPage = 5
SELECT COUNT(*) OVER() totalrow_count,*
FROM databasename
where columnname like '%abc%'
ORDER BY columnname
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
FETCH NEXT @Ro... | Get total row count while paging | [
"",
"sql",
"sql-server",
"sql-server-2012",
"paging",
"fetch",
""
] |
I have the following so far.
```
DECLARE @Table Table (ID int, Value1 varchar(50), Value2 varchar(50), Value3 varchar(50))
INSERT INTO @Table (ID, Value1, Value2, Value3)
SELECT 1, 'One', 'Uno', 'FIrst'
UNION ALL
SELECT 2, 'Two', 'Dos', 'Second'
UNION ALL
SELECT 3, 'One', 'Uno', 'Third'
UNION ALL
SELECT 4, 'Three', 'T... | Unfortunately, SQL Server doesn't have aggregate concatenation function, but you can use xml trick:
```
select
t.ID, t.Value1, t.Value2, t.Value3,
case
when count(*) over(partition by t.Value1, t.Value2) > 1 then 1
else 0
end as Duplicate,
stuff(
(
select ' - ' + TT.Value3
... | ```
SELECT *,
CASE
WHEN COUNT(*) OVER (PARTITION BY Value1, Value2) > 1 THEN 1
ELSE 0
END AS Duplicate,
CASE WHEN COUNT(*) OVER (PARTITION BY Value1, Value2) > 1
THEN STUFF((SELECT ' - ' + Value3
FROM @Table T
WHERE T.Value1 = V.Value1 ... | Concatenation - T-SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I've got a stored procedure that runs a couple queries in a `WHILE` loop, and these queries in particular take exponentially longer than the rest of the SP, greatly bogging down my performance.
I've read in a few places that using an `IN` vs. an `INNER JOIN` can improve performance if you're only pulling columns from ... | It took a bit of thinking, but I optimized this performance greatly by removing all of the `INNER JOIN`s from the relevant statements.
Relative to the time it takes to run, this query gets faster and faster based on the number of records being processed.
Here's what I ended up with. You'll notice a few extra variable... | Yes the formats are very different and they technically do different things:
This is how a join is done:
```
SELECT * FROM TABLEA a JOIN TABLEB on a.commonfield = b.commonfield
```
This is how you use an IN statement
```
SELECT * FROM TABLEA WHERE commonfield in (SELECT commonfield from tableb)
``` | How to replace an INNER JOIN with an IN? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
""
] |
I'm trying to use the SQL statement below, to retrieve data from 3 tables. I get a syntax error near [aren1002] however.
```
select
holiday_notes.*,
HOLIDAY_REF.holiday_name as holiday_name from [aren1002].[HOLIDAY_NOTES]
left join [aren1002].[HOLIDAY_REF] on holiday_notes.holiday_id=HOLIDAY_REF.holiday_id
[aren1002]... | The columns you are selecting need to be put right after the `SELECT` portion of your query, then you put the `FROM` clause next, along with any join criteria. After that, you can put your `WHERE` clause.
```
select
holiday_notes.*,
HOLIDAY_REF.holiday_name as holiday_name,
[aren1002].[lookup].lookup_desc,
[aren1002].... | You have an extra `FROM` in there.
Try this
```
select
holiday_notes.*,
HOLIDAY_REF.holiday_name as holiday_name,
[aren1002].[lookup].lookup_desc as type_desc
from [aren1002].[HOLIDAY_NOTES]
left join [aren1002].[HOLIDAY_REF] on holiday_notes.holiday_id=HOLIDAY_REF.holiday_id
left join [aren1002].[lookup] on holiday... | SQL Select from multiple tables while matching values | [
"",
"sql",
"sql-server",
""
] |
I've made an event system for my school that handles registrations for events.
Since we only want students to access sign up on the site, I've got a table called **potentialusers**. Every entry has a FullName and an Email.
When a user signs up on the site, the site checks if the student's email is in the potentialuser... | Give this a try:
```
SELECT
p.FullName,
p.Email,
IF(u.userid IS NULL, 'False', 'True') RegisteredInSystem,
IF(r.registrationid IS NULL, 'False', 'True') RegisteredInEvent
FROM potentialusers p
LEFT JOIN users ON p.Email = u.useremail
LEFT JOIN registrations r ON r.userid = u.id AND r.eventid = 7
WHERE p.FullNa... | ```
SELECT potentialusers.FullName, potentialusers.Email
, IF(users.userid IS NULL, 'False', 'True') Registered
, registration.registrationid
FROM potentialusers
LEFT JOIN users
ON potentialusers.Email = users. useremail
LEFT JOIN registrations
ON registrations.userid = users.id
WHERE potentialusers.Email LIKE '%ja... | MySQL Join two lists to check if a record exist | [
"",
"mysql",
"sql",
"join",
""
] |
I have two tables in Access database. Table1 has more columns than Table2. I would like to merge those tables into one while removing duplicates. I have the following query
```
SELECT FirstName, LastName, PhoneNumber FROM Table1
UNION
SELECT FirstName, LastName, Null as PhoneNumber FROM Table2
```
Problem is, I don'... | Start with a query which returns only those `Table2` rows which are not matched in `Table1`.
```
SELECT t2.FirstName, t2.LastName
FROM
Table2 AS t2
LEFT JOIN Table1 AS t1
ON
t2.FirstName = t1.FirstName
AND t2.LastName = t1.LastName
WHERE t1.FirstName Is Null;
```
Then use that `SELECT... | Try constraining like follows:
```
SELECT FirstName, LastName, PhoneNumber FROM Table1
UNION
SELECT FirstName, LastName, Null as PhoneNumber FROM Table2
WHERE FirstName NOT IN (SELECT FirstName FROM Table1)
AND LastName NOT IN (SELECT LastName FROM TABLE1);
``` | How do I merge two tables with different column number while removing duplicates? | [
"",
"sql",
"ms-access",
"duplicates",
"union",
"ms-access-2010",
""
] |
I have a column that contain date and for each row i would like to update only the year for example :
```
-------------
date
-------------
22/01/2013
16/02/2013
19/08/2013
23/01/2013
```
i want to change for every row only the year part like this :
```
-------------
date
-------------
22/01/2012
16/02/2012
19/08/201... | Using:
```
Update TableName set date = DateAdd(yy,-1,Date)
```
should subtract one year from each date field for you. | ```
Update table_name set date_field=DateAdd(yyyy,2012-year(date_field),date_field)
``` | How do you update only the year in and keep day and month - sql server | [
"",
"sql",
"sql-server-2008",
""
] |
So, I'm trying to create a procedure that is going to find
a specific row in my table, save the row in a result to be
returned, delete the row and afterwards return the result.
The best thing I managed to do was the following:
```
CREATE OR REPLACE FUNCTION sth(foo integer)
RETURNS TABLE(a integer, b integer, ... oth... | You just want a [DELETE...RETURNING](http://www.postgresql.org/docs/current/static/sql-delete.html).
```
DELETE FROM my_table WHERE sth_id=foo LIMIT 1 RETURNING *
```
Edit based on ahwnn's comment. Quite right too - teach me to cut + paste the query without reading it properly.
```
DELETE FROM my_table WHERE id = (S... | Can be done much easier:
```
CREATE OR REPLACE FUNCTION sth(foo integer)
RETURNS SETOF my_table
AS
$$
BEGIN
return query
DELETE FROM my_table p
where sth_id = foo
returning *;
END;
$$
LANGUAGE plpgsql;
``` | Same queries in PostgreSQL stored procedure | [
"",
"sql",
"postgresql",
"select",
"stored-procedures",
""
] |
Lets assume I have the following 'Products' table:
```
ProductID | ProductName
----------+---------
0255463 | ProductA
0254483 | ProductB
0255341 | ProductC
0905454 | ProductD
```
Is there a way (in Android's SQLite) to select each two consecutive rows into single result row?
Here is the desired query... | Create a temporary table with an auto increment column
```
CREATE TEMP TABLE temp(
id int not null primary auto increment,
pid int,
pname text,
);
```
Insert select this data into the temporary table
```
INSERT INTO temp (pid, pname) SELECT * FROM Products;
```
Join the temporary table on `id = id + 1` wh... | Single query (not faster):
```
SELECT
First.ProductId AS FirstProductId,
First.ProductName AS FirstProductName,
Second.ProductId AS SecondProductId,
Second.ProductName AS SecondProductName
FROM
(SELECT *, Cnt/2 AS Line FROM (
SELECT *, (
SELECT COUNT() FROM Products AS _ WHERE ... | select query - each two row into single result row | [
"",
"android",
"sql",
"sqlite",
""
] |
I have a column called title\_runtime that's in seconds that I want to show in hours, and also show only columns where the runtime is over three hours. This is what I have, minus the conversion:
```
select title_name, title_type, title_release_year, title_runtime as title_runtime_hrs
from nf_titles
where title_release... | If the both in the divide operation are `int` the result will be `int`.
Try this:
```
select title_name, title_type, title_release_year, title_runtime / 3600.0 as title_runtime_hrs
from nf_titles
where title_release_year = '1999' or
title_release_year = '2000' or
title_release_year = '2001' and
title_runt... | To get a precise measurement of hours, you need to divide by 3600.0. Not just 3600. If you divide by 3600 you will never get an accurate amount of hours. For example, if the runtime is an hour 1/2, you need the result to be 1.5 hours. This is not possible without dividing by 3600.0.
```
SELECT title_name, title_type, ... | Show a column that's currently in seconds in hours? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to insert two data each for each field in table as follows:
```
INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom
SELECT post_id, '_custom', 'field_514e91e73640d'
FROM `wp_temp`
WHERE custom IS NOT NULL
```
However, this doesn't work. Is there anyway to achieve thi... | ```
INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom FROM `wp_temp` WHERE custom IS NOT NULL
UNION ALL
SELECT post_id, '_custom', 'field_514e91e73640d' FROM `wp_temp` WHERE custom IS NOT NULL
``` | You will need a separate `FROM` and `WHERE` clause with each `SELECT`, but it's possible with UNION or UNION ALL.
```
INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom
FROM `wp_temp`
WHERE custom IS NOT NULL
UNION
SELECT post_id, '_custom', 'field_514e91e73640d'
FROM `wp_temp`... | How to select insert more than once using INSERT INTO? | [
"",
"mysql",
"sql",
""
] |
I have a sql query in which I am trying to get sub groups on the database and bind to a dropdown list in asp.net. On the database side I am using MSSQL server 2008 R2 and I have the below query on it:
```
SELECT -1 ItemSubGroupId,
'Select Sub Group' AS ItemSubGroupName
UNION
SELECT ItemSubGroupId,
ItemSubGroup... | It is unclear what you are asking.
I think you may be trying to have 'Select Sub Group' at the top of your list, with the rest of the list sorted alphabetically.
To do that, you would need to do something like:
```
SELECT -1, 'Select an item', 0
UNION ALL
SELECT 1, '1-test', null
UNION ALL
SELECT 2, '2-test', null
U... | You have to order both by creating a subquery
```
SELECT ItemSubGroupId, ItemSubGroupName
FROM (
SELECT -1 ItemSubGroupId,
'Select Sub Group' AS ItemSubGroupName
UNION
SELECT ItemSubGroupId,
ItemSubGroupName
FROM dbo.tblSetupItemSubGroup SG
WHERE SG.ItemMainGroupId = 17
) X
ORDER BY ... | How to sort sql query having an union statement without specific section | [
"",
"sql",
"sql-server",
"sorting",
"sql-order-by",
"union",
""
] |
When i tried to execute this stored procedure it give me is not a valid identifier error can anyone help me?
```
CREATE Proc [dbo].[AddLogtrail]
@cmodule varchar(100),
@caudittype varchar(15),
@ctable varchar(100),
@cfield varchar(100),
@cfieldtype varchar(100),
@coriginalval... | You need to add additional quotes for varchar values
```
set @SQL = 'Insert into AudittrailLog (ddatetime,cmodulename,caudittype,ctablename,cfieldname,cfieldtype,coriginalval,cnewval,cuser,creason) values ' +
'(convert(datetime,GETDATE(),105),'''+@cmodule+''','''+@caudittype+''','''+@ctable+''','''+@cfield+''','... | You need to wrap each `varchar` in '':
```
CREATE Proc [dbo].[AddLogtrail]
@cmodule varchar(100),
@caudittype varchar(15),
@ctable varchar(100),
@cfield varchar(100),
@cfieldtype varchar(100),
@coriginalval varchar(100),
@cnewval varchar(100),
@cuser varc... | Error Executing stored procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I want to update 1 column in SQL Table. Example: Current value in column is like this
```
2013/09/pizzalover.jpg
2013/10/pasta.jpg
```
Now i want to update whole column like this : www.mypizza.com/2013/09/pizzalover.jpg
Is there any way I can accomplish this? Thanks in advance | You can simply update column using statement
```
update TableName set ColumnName = 'www.mypizza.com/' + ColumnName
``` | If you are using MYSql, you can use the [`concat()`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat) as :
```
update tableName set columnName= CONCAT('www.mypizza.com/', columnName);
```
[SQLFiddle](http://sqlfiddle.com/#!2/6dd15/1)
If you are using oracle you can use the [concatenation... | How can I add text to SQL Column | [
"",
"sql",
"sql-update",
""
] |
```
<people>
<parent>
<parent-name> joel </parent-name>
<child> john </child>
<child> sara </child>
<child> ram </child>
</parent>
<parent>
<parent-name> sam </parent-name>
<child> david </child>
<child> george </child>
<child> wilson </child>
</parent>
</people>
```
the desired output is:
```
parent... | The trick is to iterate the children, then go up one level and get the parent name.
```
select a.b.value('(../parent-name)[1]','varchar(50)') as parent
, a.b.value('(.)[1]' ,'varchar(50)') as child
from @myxml.nodes('people/parent/child')a(b)
``` | You need to use `CROSS APPLY` and `.nodes()` on the `<child>` nodes of each parent node:
```
SELECT
a.b.value('(parent-name)[1]', 'varchar(50)') as parent,
XChild.value('.' ,'varchar(50)') as child
FROM
@myxml.nodes('people/parent') AS a(b)
CROSS APPLY
b.nodes('child') AS XTbl(XChild)
```
This will r... | How to retrieve all child elements for all parent elements from xml in sql | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
""
] |
So lets say I had a table of cars with attributes make and model.
Now I want to query for all cars whose model starts with the letters 'Ex'
so it would be some thing like
```
SELECT model FROM cars WHERE model = 'Ex';
```
But I guess that only returns cars whose entire model name is Ex, not whose model starts with ... | Use the [LIKE (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms179859.aspx) operator.
For example:
```
SELECT model FROM cars WHERE model like 'Ex%';
``` | You could do :
```
SELECT model FROM cars WHERE model LIKE 'Ex%';
``` | basic sql query -- where prefix = | [
"",
"sql",
""
] |
Given this script:
```
DECLARE @token NVARCHAR(max)
SET @token = 'mytexttosearchfor'
SELECT * FROM myTable WHERE myField1 LIKE '%@token%'
```
It will not work. What is the correct way to use content @token in this context? | You can use [string concatenation](http://technet.microsoft.com/en-us/library/aa276862%28v=sql.80%29.aspx), like this:
```
SELECT * FROM myTable WHERE myField1 LIKE '%'+@token+'%'
```
The reason that your approach did not work as expected is that variables are not resolved inside string literals: `'%@token%'` means a... | Try something like this
```
DECLARE @token NVARCHAR(max)
SET @token = 'mytexttosearchfor'
SELECT * FROM myTable WHERE myField1 LIKE '%' + @token + '%'
``` | SQL 2012 + LIKE + SPRINTF | [
"",
"sql",
"sql-server",
""
] |
I have a column `abc varchar(100)` with data like `2011-09-26 16:36:57.810000`
I want to convert this column to `DATETIME`...
But doing a
```
Convert(DATETIME, abc,120)
```
is giving this error:
> Conversion failed when converting date and/or time from character string.
Can any one please help me convert my `varc... | You can use style 121 but you can have **only 3 digits for milliseconds** (i.e `yyyy-mm-dd hh:mi:ss.mmm(24h)`) format.
```
declare @abc varchar(100)='2011-09-26 16:36:57.810'
select convert(datetime,@abc,121)
```
So you can sort it out by limiting the varchar field to 23 characters before converting as:
```
declare... | In case you need 6 digits precision use `DATETIME2`
```
SELECT CONVERT(DATETIME2, '2016-08-09T08:08:50.358000', 126) as MSSQLDateTime2
SELECT CONVERT(DATETIME, '2016-08-09T08:08:50.358', 126) as MSSQLDateTime
``` | Convert varchar to datetime in sql which is having millisec | [
"",
"sql",
"sql-server-2008",
""
] |
Here is my query:
```
SELECT *
FROM client_info
WHERE (cid LIKE 'G%' OR cid LIKE 'H%' OR cid LIKE 'J%')
AND (client_name NOT LIKE 'P4%' OR client_name NOT LIKE 'P5%')
```
The results still contain client names starting with P4 and P5. What is wrong with NOT LIKE clause? | Change the second set's `OR` to an `AND`.
```
AND (client_name NOT LIKE 'P4%' AND client_name NOT LIKE 'P5%')
``` | Others have given you the correct answer - you need to use AND instead of OR. But it's worth understanding why. Take a client named P5\_JONES, for instance - why is this patient showing up in the list? Because its name is NOT LIKE 'P4%'. Yes, it is like P5%, but with an OR in there, only one of those expressions needs ... | NOT LIKE clause is not working | [
"",
"mysql",
"sql",
""
] |
I want to compare two dates from two columns and get the greatest and then compare against a date value.
The two column can hold NULL values too.
For example I want the below OUTPUT.
```
Col A Col B OUTPUT
---------------------------------------
NULL NULL NULL
09/21/2013 01/... | Use Oracle [`CASE... WHEN` structure](http://www.techonthenet.com/oracle/functions/case.php) in your select:
```
SELECT COLA, COLB, CASE
WHEN (COLA >= COLB OR COLB IS NULL)
THEN COLA
ELSE COLB
END
AS OUTPUT
FROM ...
``` | Your question specifically involves two columns, but I've run into situations where I needed `GREATEST`/`LEAST` of more than two columns. In those scenarios you can use `COALESCE` and expand the solution to as many columns you want.
Here is an example with three columns `a`, `b`, and `c`:
```
GREATEST(
COALESCE(a... | Handling Null in Greatest function in Oracle | [
"",
"sql",
"oracle",
""
] |
I am hoping you can help with this question. I am using Oracle SQL (SQL Developer for this view)...
If I have a table with the following columns:
* ColumnA (Number)
* ColumnB (Number)
* ColumnC (Number)
In my view I have
```
Select
ColumnA,
ColumnB,
ColumnA + ColumnB As calccolumn1
```
Now at this point, I want ... | You could use a nested query:
```
Select
ColumnA,
ColumnB,
calccolumn1,
calccolumn1 / ColumnC as calccolumn2
From (
Select
ColumnA,
ColumnB,
ColumnC,
ColumnA + ColumnB As calccolumn1
from t42
);
```
With a row with values `3`, `4`, `5` that gives:
```
COLUMNA COLUMNB CALCCOLUMN1 CAL... | **In Sql Server**
You can do this using `cross apply`
```
Select
ColumnA,
ColumnB,
c.calccolumn1 As calccolumn1,
c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
``` | How to use a calculated column to calculate another column in the same view | [
"",
"sql",
"oracle",
""
] |
I'm sure there's a way to do this but I haven't been able to put the pieces together.
I'd like to:
```
select table_name from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'myschema';
```
and then....
```
for each table_name in that list
BEGIN
CREATE table myschemacopy.table_name like myschema.table_name;
INSERT I... | Just copy the below Query result and Run it, or you could build dynamic Query.
```
select 'select * into [newschema]. ' + table_name + ' from [myschema].' +table_name
from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA = 'myschema'
``` | If it's on the same server just a different database, you can use
SOLUTION 1 :
```
CREATE TABLE newdb.mynewtable LIKE olddb.myoldtable;
```
You can then insert data into the new table from the old using
```
INSERT newdb.mynewtable SELECT * FROM olddb.myoldtable;
[or]
```
SOLUTION 2
```
ALTER tab... | Script to copy tables and data from one schema to another in MySql | [
"",
"mysql",
"sql",
""
] |
Fist time using SQL and already confused.
I have a table :
```
A | B
--------
a | 6
b | 10
c | 12
```
I want to filter it by using string comparison, but getting the value of the second column :
```
myNum = SELECT B WHERE A ='a'
```
At the end I want the value of myNum to be 6.
Just can't get it right... any ... | You need to specify table name.
```
SELECT B from table_name WHERE A = 'a';
``` | You need the table name.
`SELECT b FROM tablename WHERE A='a';` | SQL - how to get specific value of cell? | [
"",
"mysql",
"sql",
""
] |
I want to count the values on a query result but within the same query if that makes sense. the origional query is
```
SELECT CLOSING_FEE+CLOSING_FEE_INT+CLOSING_INS+CLOSING_INT+CLOSING_OTHER as BAL, total_closing_balance
FROM statement
```
this returns over 4000 rows. I want to check the two add up. is there a way t... | try this if total\_closing\_balance is static
```
SELECT SUM(CLOSING_FEE+CLOSING_FEE_INT+CLOSING_INS+CLOSING_INT+CLOSING_OTHER) as BAL, MAX(total_closing_balance) AS total_closing_balance FROM isql.VW_300_statement WHERE brand = '1'AND DAT = '2013-01-18 00:00:00.00000'AND INS_TYPE =''group by Brand,DAT
``` | use `Select sum(CLOSING_FEE+CLOSING_FEE_INT+CLOSING_INS+CLOSING_INT+CLOSING_OTHER )`
it will add up all these details. | How to count values in a query result | [
"",
"sql",
"database",
"count",
"sybase",
""
] |
I'm trying to get the number of records from one table where a column matches another column in a `2nd` table. I then need the total values of another column that it has selected.
```
SELECT
h.holiday_id,
h.holiday_name,
CONVERT(Money,b.total_balance) AS total_balance,
b.booking_status_id,
Sum(CONVERT(Money,... | I don't really understand why need to join a table twice.
How about using `GROUP BY` , it will give the result as you expect for the `SUM` and `COUNT`.
Something like
```
SELECT
h.holiday_id,
Sum(CONVERT(Money,b.total_balance)) AS total_balance,
Count(*) AS record_count
FROM
[arend].[aren1002].[HOLIDAY_REF] ... | I would make sure you're storing total\_balance as money so you don't have to convert when displaying the data.
Even though you're using a left join, by checking that booking\_status\_id = '330' it will exclude all entries in Holiday\_Ref without a corresponding Booking entry with a status of '330'. If that is desired... | Select from 2 tables and get count totals | [
"",
"sql",
"sql-server-2008",
""
] |
From mysql [ref manual](http://dev.mysql.com/doc/refman/5.0/en/explain-output.html#explain_select_type): "Second or later SELECT statement in a UNION, dependent on outer query".
But how UNION query can be dependent on outer query? Can someone give me clear example what does it mean? For instance, in this query:
```
SE... | Well, the problem in this case is the `IN` operator, because subqueries in an `IN` clause are rewritten as correlated subqueries.
And a correlated subquery will give you a "dependent subquery" or a "dependent union" in case of an union.
See [doc](http://dev.mysql.com/doc/refman/5.7/en/subquery-restrictions.html)
> T... | Because MySQL will optimise your sql into Exists Dependent SubQuery.
As below
```
EXPLAIN SELECT *
FROM sometable
WHERE EXISTS (
(SELECT 1
WHERE sometable.id = 1) UNION (SELECT 1 WHERE sometable.id = 2)
)
``` | What is DEPENDENT UNION in select_type column from explain command? | [
"",
"mysql",
"sql",
"union",
"explain",
""
] |
I have written the following SQL Stored Procedure, and it keeps giving me the error at
`@pid = SELECT MAX(...` The whole procedure is:
```
Alter PROCEDURE insert_partyco
@pname varchar(200)
AS
BEGIN
DECLARE @pid varchar(200);
@pid = SELECT MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALU... | ```
Alter PROCEDURE insert_partyco
@pname varchar(200)
AS
BEGIN
DECLARE @pid varchar(200);
SELECT @pid = MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(@pid, @pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
```
This has an advantage over `SET` with `SELECT` in that you can select ... | ```
declare @total int
select @total = count(*) from news;
select * from news where newsid = @total+2
//**news** table name and **newsid** column name
``` | How to use SQL Variables inside a query ( SQL Server )? | [
"",
"sql",
"sql-server",
"variables",
"stored-procedures",
""
] |
The structure of **T\_TABLE2** is
```
ID INT
TBL1_ID INT
TESTER VARCHAR
LOT_ID VARCHAR
GRP VARCHAR
SITE_NUM INT
TEST_NUM VARCHAR
TEST_DESC VARCHAR
MEASUREMENT DOUBLE PRECISION
UNIT VARCHAR
LL DOUBLE PRECISION
UL DOUBLE PRECISION
STATUS VARCHAR
```
and I use SQL editor in Firebird to test my query. The query is
```
S... | You must be coming from MySQL. MySQL - IMHO misleadingly, incorrectly, and in a black-magicky, unpredictible sort of way - allows you to specify partial `GROUP BY` queries and the database engine tries to figure out from the rest of the query *which* value of the non-grouped-by columns you want. Standard SQL (Firebird ... | While some databases, such as MySQL, are more lenient, in standard SQL when you use `GROUP BY`, the `SELECT` list must only contain the columns being grouped by and aggregate functions (e.g. `SUM()`, `MAX()`). If you were allowed to specify other columns, it's unpredictable which of the rows of the grouped column these... | How to use GROUP BY in Firebird? | [
"",
"sql",
"group-by",
"firebird",
""
] |
I've got a very complicated answer about my question here:
[Select a record just if the one before it has a lower value](https://stackoverflow.com/questions/18801262/select-a-record-just-if-the-one-before-it-has-a-lower-value)
about 3 weeks ago.
now I'm troubled with altering this query.
so this is the final versio... | Looking into this, the following way is possibly a quicker way of doing the basic select than you are already using:-
```
SELECT AfterSub.ID,
AfterSub.SerialNumber,
BeforeSub.Remain_Toner_Black BeforeCount,
AfterSub.Remain_Toner_Black AfterCount
FROM
(
SELECT ID, SerialNumber, Remain_Toner_Black, @Co... | Please place index on A.time and use this
```
SELECT a.ID, DATE_FORMAT(a.Time,'%d/%m/%y') AS T, a.SerialNumber,
b.Remain_Toner_Black BeforeCount,
a.Remain_Toner_Black AfterCount
FROM
(
SELECT a.ID,
a.Time,
a.SerialNumber,
a.Remain_Toner_Blac... | Select a record just if the one before it has a lower value filtered by month | [
"",
"mysql",
"sql",
""
] |
I have a table with ID's from 1 to 20 and I need to fetch 10 rows (random), but 3 of the 10 rows are predefined and needs to be at the beginning of the result list - In one MySQL statement:
This works, but the production table contains over 500K rows:
```
SELECT id
FROM tableName
WHERE id IN (1,2,3,4,5,6,7,8,9,10,11... | You can use statement like this:
```
SELECT
id
FROM
(
SELECT
id,
IF(id IN (5,6,7),1,0) AS priority
FROM tableName
) t
ORDER BY priority DESC, RAND()
LIMIT 10
``` | If UNION ALL is allowed, you could try something like this:
```
select id from tablename where id in (compulsary_1, compulsary_2, compulsary_3)
order by id desc
union all
select id from tablename where id not in (compulsary_1, compulsary_2, compulsary_3)
order by rand() limit 7
``` | MySQL fetch 10 randomly rows where 3 predefined rows needs to be part of the results and be at the beginning | [
"",
"mysql",
"sql",
""
] |
I have a stored procedure which needs a different if condition to work properly.
The procedure has 2 parameter namely, @CategoryID and @ClassID, which basically come from a UI tree view functionality. @CategoryID corresponds to the parent nodes, while @ClassID corresponds to the child nodes.
Based upon the above para... | If I understand the question correctly, what you require in your result set is:
(all supplied classid) + (all classid for supplied categoryid with no matching supplied classid)
That would translate to the following:
```
CREATE PROCEDURE [dbo].[uspGetCodes]
(
@CategoryID varchar(50),
@ClassID varchar(50)
)
AS... | this is the sample query that can achieve your goal, is this what you want?
```
DECLARE @SAMPLE TABLE
(
ID INT IDENTITY(1,1),
CategoryId INT,
ClassID INT
)
INSERT INTO @sample
VALUES(2,10)
INSERT INTO @sample
VALUES(2,11)
INSERT INTO @sample
VALUES(2,12)
INSERT INTO @sample
VALUES(3,13)
DECLARE @CategoryID INT
DECLA... | Complex SQL selection query | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"if-statement",
""
] |
I have this table:
Playing(Date,Time,Location,Name,TeamName,ShirtColor)
And I want to select all teams that wore exactly two different shirt colors.
Since I dont have SQL DB, I'd like to ask which of these two (or maybe none of them) is correct and why?
1. `SELECT (DISTINCT TeamName)
FROM Playing
WHERE Te... | Unfortunately, none of your queries are correct from a syntactic point of view.
Here is a **[SQLFiddle](http://sqlfiddle.com/#!3/149ea/4)** with sample data, and with the query that you are looking for
```
SELECT TeamName
FROM Playing
GROUP BY TeamName
HAVING COUNT(DISTINCT ShirtColor) = 2
```
When you GROUP reco... | You don't need a subquery:
```
SELECT TeamName
FROM Playing
GROUP BY TeamName
HAVING COUNT(DISTINCT ShirtColor) = 2
``` | SQL - Select all teams that wore exactly two different shirt colors? | [
"",
"sql",
""
] |
I'm having trouble creating a query with a sub query to find the one customer in my DB who has made the most purchases. I need to list his/her full name, product name, price and quantity. Here is what I have so far
```
select first_name ||' '|| last_name "FullName", pt.name p.price, sum(ps.quantity)
from customers c... | Here's one way to do it. It uses an analytic function to order customers by the total quantity of purchases: `row_number() over (order by sum(quantity) desc)`. If there's more than one person with the same quantity, this will pick out only one.
It then takes this customer id and joins the rest of the tables in the obv... | Here is the general idea. You can adapt it for your database tables.
```
select fred, barney, maxwilma
from bedrock join
(select max(wilma) maxwilma
from bedrock
group by fred ) flinstone on wilma = maxwilma
``` | Subquery "Finding customer who has the most purchases" | [
"",
"sql",
"oracle",
""
] |
I'm working on a project as an outsourcing developer where i don't have access to testing and production servers only the development environment.
To deploy changes i have to create sql scripts containing the changes to make on each server for the feature i wish to deploy.
**Examples:**
* When i make each change on ... | Look into Liquibase specially at the SQL format and see if that gives you what you want. I use it for our database and it's great.
You can store all your objects in separate scripts, but when you do a Liquibase "build" it will generate one SQL script with all your changes in it. The really important part is getting yo... | I can tell you how we at xSQL Software do this using our tools:
* deployment team has an automated process that takes a schema snapshot of the staging and production databases and dumps the snapshots nightly on a share that the development team has access to.
* every morning the developers have up to date schema snaps... | How to manage/ track changes to SQL Server database without compare tool | [
"",
"sql",
"sql-server",
"deployment",
"compare",
""
] |
Let's pretend we have this relation:
```
╔═══════════════════╗
║ i++ name score ║
╠═══════════════════╣
║ 1 Will 123 ║
║ 2 Joe 100 ║
║ 3 Bill 99 ║
║ 4 Max 89 ║
║ 5 Jan 43 ║
║ 6 Susi 42 ║
║ 7 Chris 11 ║
║ 8 Noa 9 ║
║ 9 Sisi 4 ║
╚═════════════... | If you do not need the rank in your output (and it appears from your comments and favored answers that you do not), you can simply combine the quiz scores nearest to Jan's score:
Query ([SQL Fiddle here](http://sqlfiddle.com/#!2/76ad1/11)):
```
-- XXX this assumes `scores`.`username` is UNIQUE !
SELECT * FROM (
-... | It's not entirely clear what you want, but a creative use of limit might be able to help:
```
Set @i = 0;
Select
(@i := @i + 1) + 2 place,
s.*
From
quiz_score s
Order By
quality Desc
Limit
2, 5;
```
**`Example Fiddle`** | sql show partition based on calculated column with mysql | [
"",
"mysql",
"sql",
"ranking",
""
] |
I have a table containing data about events and festivals with following columns recording their start and end dates.
* Start\_Date
* End\_Date
date format is in `YYYY-MM-DD`. I need to fetch event details with the following condition.
* Need to fetch all events which start with a current month and there end dates c... | ```
select * from your_table
where year(Start_Date) = year(curdate())
and month(Start_Date) = month(curdate())
and end_date <= curdate() + interval 30 day
``` | I don't like either of the other two answers, because they do not let the optimizer use an index on `start_date`. For that, the functions need to be on the current date side.
So, I would go for:
```
where start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curda... | comparing dates by month and year in mysql | [
"",
"mysql",
"sql",
""
] |
I have a table with columns `date` and `time_spent`. I want to find for each date D the sum of the values of 'time\_spent' for the period of time : (D-7 - D), ie. past week + current day.
I can't figure out a way to do this, as I can only find examples for a total sum and not a sum over a variable period of time.
Her... | And one more solution
```
SELECT r1.date, r1.time_spent, sum(r2.time_spent) AS rolling_week_total
FROM rolling_total AS r1 JOIN rolling_total AS r2
ON datediff(r1.date, r2.date) BETWEEN 0 AND 7
GROUP BY r1.date
ORDER BY r1.date
LIMIT 8
``` | MySQL 8 has [window functions](https://dev.mysql.com/doc/refman/8.0/en/window-functions-frames.html) that are meant for this exact case:
```
SELECT
SUM(time_spent) OVER(
ORDER BY date RANGE BETWEEN INTERVAL 7 DAY PRECEDING
AND CURRENT ROW) AS total,
date
FROM rolling_total
```
`ORDER BY` da... | Create a ROLLING sum over a period of time in mysql | [
"",
"mysql",
"sql",
"sum",
"query-optimization",
"rolling-computation",
""
] |
i have a select statement which always returns only 3 rows. One column has static values RED AMBER and GREEN.
<http://sqlfiddle.com/#!6/5e107/2>
In the fiddle link, i have a sample code.
```
select color,SUM(clrcount) from
tmp group by color
```
returns 3 rows on execution.
But if i delete items marked AMBER, an... | Redesigning would be a better approach but if you can't do it now and certain about those three colours, try something like this :
**[Fiddle demo](http://sqlfiddle.com/#!6/0e59b/5)**
```
select t.color,coalesce(sum(clrcount),0) colorCount
from tmp right join
(values('RED'),('AMBER'),('GREEN')) As t(color)
... | Rather than deleting amber rows you need to set clrcount = 0 for those rows - this will work with your current query.
However, if they must be deleted then the answer by Joel Coehoorn is your way to go. | select statement to always return 3 rows on execution | [
"",
"sql",
"sql-server",
"select",
""
] |
Am trying to retrieve data from Database in Ascending order.
My query was
```
select pid
from `patient_list` t1, patient_info t2
where pid > '2000' and t2.id=t1.id
order by pid asc
limit 10
```
but the data is like
```
pid
2221
2223
2224
2227
**223**
2238
2239
2242
2245
2247
**225**
```
How to sort this ? | Firstly, clean the data. Secondly, cast to int. Thirdly sort and/or filter.
```
select pid from `patient_list` t1, patient_info t2
where replace(pid, "*", "") + 0 > 2000 and t2.id = t1.id
order by replace(pid, "*", "") + 0
limit 1
```
Note that you are also filtering on that field so you should use the replacement ... | Your data is sorted alphanumeric. To force a numerical sort you must cast the data into a number. For instance with `pid * 1`
```
select pid
from `patient_list` t1, patient_info t2
where pid > '2000'
and t2.id=t1.id
order by pid * 1 asc
limit 1
```
Since your `pid` is of a string type you should consider changin... | how to sort this data by in ascending order? | [
"",
"mysql",
"sql",
""
] |
I have a table which has a doctor\_id, patient\_id, date\_of\_visit and comments.
```
doctor_id|Patient_id |date_of_visit | comments
------------------------------------------------
1 | 11 | 12-12-2012 | abcdef
2 | 12 | 12-13-2012 | erewrwq
1 | 13 | 12-12-2012 | dsfsdf
3... | ```
select doctor_id
from your_table
group by doctor_id, date_of_visit
having count(*) = 3
``` | ```
SELECT count(doctor_id)
FROM table_name
WHERE doctor_id=1
and date=12-12-2012
``` | Find number of visits on each day | [
"",
"sql",
"oracle",
""
] |
Basically I have three MySQL tables:
**Users** - contains base information on users
**Fields** - describes additional fields for said users (e.g. location, dob etc.)
**Data** - Contains user data described via links to the fields table
With the basic design as follows (the below is a stripped down version)
**Use... | I'm going with the assumption that "searching multiple fields" is talking about the [Entity-Attribute-Value structure](http://en.wikipedia.org/wiki/Entity%2Dattribute%2Dvalue_model).
In that case, I propose that the first step is to create a derived query - basically, we want to limit the "EAV data joined" to *only* i... | If I understood you right, this is what you want:
```
FROM `users`,
`fields`,
`data` `location`
`data` `name`
WHERE `location`.`Field_ID` = '2'
AND `location`.`value` LIKE 'london'
AND `location`.`Field_ID` = `fields`.`ID`
AND `name`.`Field_ID` = 'whathere? something for its name'
AND `name`.`value` LI... | Search a table based on multiple rows in another table | [
"",
"mysql",
"sql",
"entity-attribute-value",
"relational-division",
""
] |
I cant get the understanding of this statement - not eveN after googling around
```
pv_no_list :='23,34,45,56';
SELECT DISTINCT REGEXP_SUBSTR (pv_no_list,
'[^,]+',
1,
... | The "abuse" (as Colin 't Hart put it) of `connected by` has a good purpose here:
by using `REGEXP_SUBSTR` you can extract only one of the 4 matches (23,34,45,56): the regex `[^,]+` matches any character sequence in the string which does not contain a comma.
If you'll try running:
```
SELECT REGEXP_SUBSTR ('23,34,45,5... | `connect by` has nothing to do with `regex_substr`:
* The first is to perform a hierarchical query, see <http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm>
* The second is to get a substring using regular expressions.
This query "abuses" the `connect by` functionality to generate rows in a query on... | connect by clause in regex_substr | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
In Oracle, I have columns called orderids
```
orderids
111,222,333
444,55,66
77,77
```
How can get the output as
```
Orderid
111
222
333
444
55
66
77
77
``` | Try this:
```
WITH TT AS
(SELECT orderid COL1 FROM orders)
SELECT substr(str,
instr(str, ',', 1, LEVEL) + 1,
instr(str, ',', 1, LEVEL + 1) -
instr(str, ',', 1, LEVEL) - 1) COL1
FROM (SELECT rownum AS r,
','|| COL1||',' AS STR
... | This is one appraoch:
```
with order_table as (
select '111,222,333' as orderids from dual
union all select '444,55,66' from dual
union all select '77,77' from dual
)
select substr(orderids, instr(orderids, ',', 1, lvl) + 1, instr(orderids, ',', 1, lvl + 1) - instr(orderids, ',', 1, lvl) - 1) orderid
from
( s... | Split comma separated values in Oracle 9i | [
"",
"sql",
"oracle",
"oracle9i",
""
] |
Good day everyone. Here is my code:
```
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.fld_LOAN)) as [Month]
,COUNT(PIT.fld_ID)'COUNT'
,SUM (PIT.fld_GRAM)'GRAMS'
,SUM (PH.fld_AMNT)'PRINCIPAL'
FROM #AllExpired AE
INNER JOIN Transactions.tbl_ITEM PIT
ON AE.fld_MAINID=PIT.fld_MAINID
IN... | You cannot expect any records to be outputted when using a GROUP BY clause, when no records exist in your source.
If you want an output of 0 from the SUM and COUNT functions, then you should not use GROUP BY.
The reason is that when you have no records, the GROUP BY clause has nothing to group by, and then is not abl... | I would imagine you need to change your joins from INNER to OUTER to ensure rows are returned even when there is no corresponding record in tbl\_PawnItem -
```
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.fld_LoanDate)) as [Month]
,COUNT(PIT.fld_PawnItemID)'COUNT'
,SUM (PIT.fld_KaratGram)'GRAMS'
... | Count Returning blank instead of 0 | [
"",
"sql",
"t-sql",
"count",
"sql-server-2008-r2",
"sum",
""
] |
I am trying to use a result of a string split to where close in my sql condition
I have table which has a `varchar` column. I am trying to filter the result where there is only one word is presented.
eg. if the table have values like *'ABC DEF','XYZ','EGF HIJ'* and I am expecting to get only *'XYZ'* as result.
I am ... | To get only 'XYZ' in the with a column containing
```
tableName.fieldName
'ABC DEF'
'XYZ'
'EGF HIJ'
```
Do this
```
SELECT *
FROM tableName
WHERE CHARINDEX(' ',fieldname) = 0
``` | ***This is also work***
```
select SUBSTRING(EmpName,0,CHARINDEX(' ',EmpName)),SUBSTRING(EmpName,CHARINDEX(' ',EmpName),LEN(EMPNAME))
from tblemployee
``` | Split string by space | [
"",
"sql",
"sql-server-2008",
"split",
""
] |
I'm trying to select the last `enddate` per `nr`. In case the `nr` contains an `enddate` with value `NULL`, it means this `nr` is still active. In short I cannot use `MAX(enddate)` because out of `2013-09-25` and `NULL` it would select the date whereas I need `NULL`.
I tried the following query though it seems that `N... | You can use the query below. It returns NULL before other dates (provided that you put a date great enough) and then restores NULL.
```
SELECT nr, CASE d WHEN '20990101' THEN NULL ELSE d END d
FROM (
SELECT nr,
CASE MAX(ISNULL(enddate, '20990101') d
FROM myTable
GROUP BY nr
)
```
I couldn't check the ... | You could use this query. The CTE calculates the maximum date ignoring any nulls, this is then left joined back to the table to see if there is a null value for each nr value. The case statement returns a null if it exists or the maximum date from the CTE.
```
WITH CTE1 AS
(SELECT nr, MAX(enddate) MaxEnddate
FROM myT... | Array contains NULL value | [
"",
"sql",
"sql-server",
"arrays",
"null",
"expression",
""
] |
Sorry I know you want example code but unfortunately, I have absolutely no idea how I can implement this functionality or for what I have to search for.
Let's pretend we have this relation:
```
╔═══════════════════╗
║ id name quality ║
╠═══════════════════╣
║ 1 Will 4 ║
║ 2 Joe 9 ║
║ 3 Bill 2 ... | Assuming the ID field is always in a preset order (two before and two after the specific row can be counted via the ID field), you can do one of two simple queries:
```
SELECT *
FROM tbl1
WHERE id BETWEEN 3 AND 7
```
(An SQL Fiddle demo can be found [here](http://sqlfiddle.com/#!2/126a4/2))
or:
```
SET @a:=5; ... | ```
SET @search_id = 5;
SELECT *
FROM my_table
WHERE id BETWEEN (@search_id - 2) AND (@search_id + 2);
``` | sql show partition based on found record in mysql | [
"",
"mysql",
"sql",
""
] |
I'm working on my project in php [handling students attendance system]. I have a list of students along with their unique id[`jntuno`] and I need to create a database in mysql for storing the daily attendance of each student for each subject. So I created my tables in this way :
I have a table `students` in mysql with... | Create the new table with the following statements:
```
select @s:=concat('create table students_col (',group_concat(jntunno,' CHAR(10)' order by slno),')') from students;
prepare stmt from @s;
execute stmt;
deallocate prepare stmt;
```
observe how the `CREATE TABLE` is constructed using the `group_concat`
Demo: [SQ... | This procedure will do the work:
```
DELIMITER ||
DROP PROCEDURE IF EXISTS `test`.`pivot`;
CREATE PROCEDURE `test`.`pivot`()
MODIFIES SQL DATA
BEGIN
DROP TABLE IF EXISTS `test`.`new_table`;
SELECT GROUP_CONCAT(CONCAT(`jntunno`, ' CHAR(10) NOT NULL') SEPARATOR ', ') FROM `test`.`students` INTO @sql;
SET... | Creating columns of a table using the rows of another | [
"",
"mysql",
"sql",
"database-design",
"pivot-table",
""
] |
Let's say I was looking for the second most highest record.
Sample Table:
```
CREATE TABLE `my_table` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`value` int(10),
PRIMARY KEY (`id`)
);
INSERT INTO `my_table` (`id`, `name`, `value`) VALUES (NULL, 'foo', '200'), (NULL, 'bar', '1... | This only works for **exactly** the second highest:
```
SELECT * FROM my_table two
WHERE EXISTS (
SELECT * FROM my_table one
WHERE one.value > two.value
AND NOT EXISTS (
SELECT * FROM my_table zero
WHERE zero.value > one.value
)
)... | Eduardo's solution in standard SQL
```
select *
from (
select id,
name,
value,
row_number() over (order by value) as rn
from my_table t
) t
where rn = 1 -- can pick any row using this
```
This works on any modern DBMS except MySQL. This solution is usually faster than solutions u... | How many different ways are there to get the second row in a SQL search? | [
"",
"mysql",
"sql",
""
] |
I have three MySQL tables: 'people', 'people2id', 'places'. The first one stores information about people, where the 'places' table stores information about their addresses. The middle one, 'people2id', interconnects this two tables (could be that one person has two or more addresses).
Now I want to go to some person'... | Change the `JOIN` to `LEFT JOIN`, i.e.
```
SELECT * FROM people p
LEFT JOIN people2id e ON p.peopleId = e.peopleId
LEFT JOIN places a ON a.peopleId = e.peopleId
WHERE p.peopleId = number
```
Using `LEFT JOIN` will include all the records from `people`, whether they contain associated records or not. | **UNION** is used for get same kind of informations from two different queries and return them as a single result set
**JOIN** is used for *add columns and data to rows* (not as simple but you can see it like this) | Confused about using UNION or JOIN | [
"",
"mysql",
"sql",
"database-design",
"join",
"union",
""
] |
Let's say I have the following schema
```
Company:
-> company_id
-> company_name
Building_to_company:
-> building_id
-> company_id
```
So each building has its own id as well as a company id which relates it to a single company.
the following query gives two columns -- one for the company name, and then its associa... | You've basically got it in words already. Assuming `company_name` is unique, all you have to add to your explanation to get it to work is a `GROUP BY` clause:
```
SELECT company.company_name, COUNT(building_to_company.building_id)
FROM company
INNER JOIN building_to_company
ON company.company_id = building_to_com... | I think you want something like this
```
SELECT c.company_name, count(b.building_id)
FROM
company as c,
building_to_company as b
WHERE c.company_id = b.company_id
GROUP BY c.company_name;
``` | Pretty basic SQL query involving count | [
"",
"mysql",
"sql",
""
] |
I have a lot of stored procedures. But I am only getting Request Timeout sometimes only for this SP ?
```
ALTER PROCEDURE [dbo].[Insertorupdatedevicecatalog]
(@OS NVARCHAR(50)
,@UniqueID VARCHAR(500)
,@Longitude FLOAT
,@... | The timeout occurs due to two updates to same table inside same transaction. You could avoid it with a case statement. Also whole IF ELSE can be replaced with a merge.
```
MERGE INTO DeviceCatalog DC
USING (SELECT @UniqueID AS UniqueID) T ON (DC.UniqueID = T.UniqueID)
WHEN MATCHED THEN
UPDATE SET [OS] = @OS
... | Already discussed [here](http://social.msdn.microsoft.com/Forums/sqlserver/en-US/cd804f22-875e-484f-b425-2a0acd9c0111/limiting-concurrent-execution-of-a-tsql-stored-procedure)
You can achieve it using sp\_getapplock in TSQL.
But you need a wrapper storedproc or batch for this. Check the following example it will help... | Getting Request Timeout sometimes from only one SP? | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
I have a table with products and each product has: brand, collection, name.
I want users to search through the products but I would like to search all three fields for those searchwords because the user probably won't always know if their searchword is for brand, collection or name. A user can easily be searching for '... | It looks like what you need is a full text search: <http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html>
```
SELECT * FROM products WHERE MATCH (brand, collection, name) AGAINST ('+searchname +searchbrand' IN BOOLEAN MODE)
```
For a better performance, you still could create a separate table with one field c... | MySQL provides FULLTEXT, please refer to this link to know more on this
<http://www.petefreitag.com/item/477.c> | Need tip on searching through multiple fields [mysql optimization] | [
"",
"mysql",
"sql",
"performance",
"search",
""
] |
I have the following `Split` function,
```
ALTER FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
set @String = RTRIM(LTRIM(@String))
declare @idx int
... | A simpler function:
```
CREATE FUNCTION dbo.SplitStrings_Ordered
(
@List nvarchar(MAX),
@Delimiter nvarchar(255)
)
RETURNS TABLE
AS
RETURN
(
SELECT [Index] = CHARINDEX(@Delimiter, @List + @Delimiter, Number),
Item = SUBSTRING(@List, Number, CHARINDEX(@Delimiter,
@List + @Del... | Your function will need to set an order column (seq in this sample):
```
ALTER FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (seq int, items varchar(8000))
as
begin
set @String = RTRIM(LTRIM(@String))
declar... | SQL Split Function and Ordering Issue? | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
i ve the following oracle sentence that returns grouped results, for example 10 of one group, 8 of second group.
I am having trouble counting them, as it seems that this count(\*) as stevilo\_prosenj doesnt work properly, so i would appreciate if someone can help me how to get the result count of how many there are in... | I'm going to assume that you want a GROUP BY, but not on all of your SELECTed columns...
If your database supports it, you could
```
SELECT columnA, columnB, columnC, count(*) OVER (PARTITION BY columnA, columnB)
FROM table;
```
and otherwise, you'll have to select it manually
```
SELECT a.columnA, a.columnB, a.col... | You join tables in your FROM statement but `S_STUDENTSKI_DOMOVI_VW stdm, MSB_SIF_STATUSOV_PROSENJ sifstat` tables aren't connected to others in the WHERE statement so they connect with all rows and you get FULL JOIN without conditions so COUNT outputs results you haven't expected (Multiplied to both tables row counts). | Oracle count * and groupBy | [
"",
"sql",
"count",
"group-by",
""
] |
Suppose a Nested query is like :
```
SELECT *
FROM Table1
WHERE Table1.val in
(
Select Table2.val
from Table2
where Table2.val>3
)
```
So my question is how do actual query processors evaluate this -
* Do they first evaluate inner most query, store the result temporarily and then use it in the upper le... | It depends. You're allowed to reference a value from the outer query inside the inner. If you do this, you have what is referred to as a *correlated sub-query* or *correlated derived table*. In this case, it has to recompute the query for every possible row in the parent query. If you don't this, you have what is refer... | This might help you
There is plenty of memory available to run fairly large queries and there is little chance of the query's complexity creating a timeout. Nested queries have the advantage of being run almost exclusively in physical memory for the sake of speed, unless the amount of memory needed to perform the quer... | SQL Nested Query Processing | [
"",
"mysql",
"sql",
""
] |
Hi I currently have 3 tables as listed below. There is no common keys between the tables
Table 1->linkage\_Table
```
ID Item Material Color
1 keypouch * yellow
2 wallet plastic *
3 card-holder leather gold
```
Table 2->Material\_Table
```
ID Name
1 p... | One possible approach:
```
SELECT l.Item, m.name, c.Color
FROM linkage_Table AS l
INNER JOIN Material_Table AS m
ON l.Material = '*'
OR l.Material = m.name
INNER JOIN Color_Table AS c
ON l.Color = '*'
OR l.Color = c.Color
```
[**SQL Fiddle**](http://sqlfiddle.com/#!2/67c33/... | With example:
```
CREATE TABLE linkage_table (
id INT,
item VARCHAR(40),
material VARCHAR(40),
color VARCHAR(40)
);
CREATE TABLE material_table (
id INT,
name VARCHAR(40)
);
CREATE TABLE color_table (
id INT,
color VARCHAR(40)
);
INSERT INTO linkage_table VALUES (1, 'keypouch', '*', 'yellow');
INSER... | Joining multiple tables without common key | [
"",
"mysql",
"sql",
""
] |
I have two tables:
```
case(caseId,judge,verdict)
appeal(caseId,verdict)
```
And I want to select all judges that had their verdict changed at least half of the times (for example, if a judge presided in 5 cases and 3 of his verdicts were changed in the appeal, I want to select him).
I tried to solve it using neste... | ```
select *
from (
select c.caseid,
c.verdict,
c.judge,
count(*) over (partition by c.judge) as total_cases_per_judge,
sum(
case
when (c.verdict <> coalesce(a.verdict, -1)) then 1
else 0
end) over (partition by c.judge) ... | Probably you can try something like:
```
SELECT n.judge FROM (
SELECT s.judge, COUNT(*) AS total, COUNT(s.changed_verdict) AS changed FROM (
SELECT c.caseId, c.judge, c.verdict, a.verdict AS changed_verdict FROM case c
LEFT JOIN appeal a ON a.caseId = c.caseId AND a.verdict != c.verdict
) s... | Select all judges that had their verdict changed at least half of the times | [
"",
"sql",
""
] |
I was doing some homework for my security class involving SQL injections. I found that I could do a shorter SQL injection than the typical `' OR '1'=1` example. Instead I could do `'='`. Typing this is in to the password field of a typical login boxes gives a SQL query like this:
```
SELECT * FROM Users WHERE username... | As documented under [Type Conversion in Expression Evaluation](http://dev.mysql.com/doc/en/type-conversion.html), comparisons between a string and an integer will be performed numerically:
> * In all other cases, the arguments are compared as floating-point (real) numbers.
Therefore, the operands are converted to flo... | Mysql sees the comparison and converts the string to an integer,but this results in an invalid integer so it cast it to 0. 0=0 so its true(1) | Why does SELECT 'a'='b'='c' return 1 in MYSQL? | [
"",
"mysql",
"sql",
"sql-injection",
""
] |
I have this data:
```
id worked_date
-----------------
1 2013-09-25
2 2013-09-26
3 2013-10-01
4 2013-10-04
5 2013-10-07
```
I want to add a column called `weekCount`. The based date is `2013-09-25`. So all the data with worked\_date from `2013-09-25 to 2013-10-01` will have `weekCount` as 1... | Perhaps an approach like this will solve your problem.
I compute an in-memory table that contains the week's boundaries along with a monotonically increasing number (BuildWeeks). I then compare my `worked_date` values to my date boundaries. Based on your comment to @sgeddes, you need the reverse week number so I then ... | Here's one way using `DATEDIFF`:
```
select id,
worked_date,
1 + (datediff(day, '2013-09-25', worked_date) / 7) weekCount
from yourtable
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!6/c881c/6) | Create a weekCount column in SQL Server 2012 | [
"",
"sql",
"sql-server-2012",
""
] |
I am stuck on a SQL query. I am using PostgreSQL. I need to get the total for each month for all states.
```
table A
--------------------------------------------------------
created | Name | Agent_id | Total
--------------------------------------------------------
3/14/2013 | Harun | 1A | 5 ... | to have all state with no data in table A / B you have to use `OUTER JOIN`
to complete @bma answer
```
select
no,
state,
sum(case when month = 1 then total else 0 end) as januari,
sum(case when month = 2 then total else 0 end) as februari,
sum(case when month = 3 then total else 0 end) as mars,
sum(ca... | Something like the following should give you results like your sample results. I'm not sure what the "No" column was though. This query is untested.
```
select state,
sum(case when mm = 1 then total else 0 end) as jan,
sum(case when mm = 2 then total else 0 end) as feb,
sum(case when mm = 3 th... | SQL query to calculate total per month as a column | [
"",
"sql",
"postgresql",
"pivot",
""
] |
I am trying to display a list of players from team #1 and the stats to go with them, here are the tables
table 1: players
```
╔═══════════════════════════╗
║ id | fname | lname | team ║
╠═══════════════════════════╣
║ 1 | Jason | McFee | 1 ║
║ 2 | John | Smith | 1 ║
║ 3 | Jack | Doe | 1 ║
║ 4 | Wayne ... | This is the query you're looking for:
```
SELECT
p.id,
CONCAT_WS(', ', SUBSTR(p.fname, 1, 1), p.lname) name,
COALESCE(eg_goals.goals, 0) goals,
COALESCE(eg_assists1.assists, 0) + COALESCE(eg_assists2.assists, 0) assists,
COALESCE(eg_goals.goals, 0) + COALESCE(eg_assists1.assists, 0) + COALESCE(eg_assists2.a... | You need to add a [GROUP BY](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html) (see also [SQL GROUP BY Statement](http://www.w3schools.com/sql/sql_groupby.asp))
> The GROUP BY statement is used in conjunction with the aggregate
> functions to group the result-set by one or more columns.
```
**SQL GROUP ... | SQL Joining rows after using count | [
"",
"mysql",
"sql",
"join",
"count",
"union",
""
] |
**UPDATE: We were advised that it is possible that values for both parameters will not be provided. In such case, there should be no filter for both mobile number and email address.**
I'm having a hard time identifying what's wrong with my query. Basically, I have two variables
```
@EmlAdd
@MblNum
```
What I want to... | Try this one -
```
DECLARE
@EmlAdd VARCHAR(100)
, @MblNum VARCHAR(100)
SELECT
@EmlAdd = ''
, @MblNum = '5555555'
SELECT [USER_ID], CONTACT_VALUE
FROM dbo.TBL_CONTACTS
WHERE CONTACT_VALUE IN (@MblNum, @EmlAdd)
``` | Remove the **OR @MblNum = ''** and **OR @EmlAdd = ''**
When only one parameter has a value set the other will equal **''** (0 length string) and therefore the logical condition will be met on every call.
```
DECLARE
@EmlAdd AS VARCHAR(100),
@MblNum AS VARCHAR(100)
SET @EmlAdd = ''
SET @MblNum = '5555555'
SELECT
... | SQL: Conditional where clause not working | [
"",
"sql",
"sql-server",
"variables",
"where-clause",
""
] |
i'm trying to run the following query that counts the number of doctors with patient referrals within the last 6 months:
```
SELECT
count(local_doc.providerno) NumberofReferals,
LOCAL_DOC.FULLNAME FULLNAME,
LOCAL_DOC.TELNUMBER TELNUMBER,
LOCAL_DOC.STREET STREET,
LOCAL_DOC.SUBURB SUBURB,
L... | > Dear, group By Clause ask a user to specify all Select Columns in
> Group By Clause as well except select columns with aggregated
> functions.
>
> Look in my Group by Clause i have specify all columns in Select except
> **local\_doc.providerno** because it is using **Aggregated function COUNT**
For better understand... | add
```
GROUP BY
LOCAL_DOC.FULLNAME ,
LOCAL_DOC.TELNUMBER ,
LOCAL_DOC.STREET ,
LOCAL_DOC.SUBURB ,
LOCAL_DOC.STATE ,
LOCAL_DOC.POSTCODE ,
LOCAL_DOC.PROVIDERNO
```
Most DBS other than MYSql will require you to group on the remaining selected columns | oracle sql not a group by expression while counting | [
"",
"sql",
"oracle",
"ora-00979",
""
] |
I'm trying to accumulate a Year to Date total of the number of incident events in a SQL Server shipping system, for display in a graph.
What I have at the moment:
```
SELECT EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM Event
INNER JOIN
PortEvent ON Event.PortEventID = PortEvent.ID
... | You have problem in you `EventType ON PortEvent.EventID = Event.ID` condition.The query below must solve your issue.
```
SELECT ET.Name AS [Incident Name], COUNT(E.ID) AS [Occurrence]
FROM EventType ET
LEFT JOIN PortEvent PE
ON ET.ID = PE.EventID
LEFT JOIN Event E
ON PE.EventID = E.ID
AND E.IsInciden... | Simply using left joins is insufficient. You need to re-order your query so all event types are in the left-most recordset (that's how I visualize it anyway). Additionally, you need to get rid of the where clause and add it to the event table's join because, if not, it might as well be an inner join.
```
SELECT
Ev... | Display Rows that Have a 0 count | [
"",
"sql",
"sql-server",
"count",
""
] |
Good Morning all;
I have the following table
```
Date Duration COT TD RID
6/26 30 PT OT 1
6/26 15 OT PT 1
6/27 60 PT OT 1
6/27 60 ... | You were almost there. Just use the AS keyword to alias the table into two different names and then use the criteria you put forward in your question as follows.
```
Select * from Table as T1
Join Table as T2 on T1.TD = T2.COT
AND T1.COT= T2.TD
AND T1.Duration <> T2.Duration
AND T1.Date = T2.Date
AND T1.RID = T2.RID... | You may need to set criteria about which row you like in final output. Below are some some examples:
If you need any random row in final output:
```
Select top 1 * from t1 as T1
Join t1 as T2 on T1.TD = T2.COT
AND T1.COT= T2.TD
AND T1.Duration <> T2.Duration
AND T1.Date1 = T2.Date1
AND T1.RID = T2.RID
```
If you c... | Getting a single result from table with multiple comparisons | [
"",
"sql",
""
] |
I have two user SQL tables with more or less the same data in it and I want to merge the two tables and only take the user with the highest `MyLevel`. Maybe it makes more sense if I show what I have and what I want.
Table One:
```
MyName, MyDescr, MyLevel, FromDB
John, "Hey 1", 100, DB1
Glen, "Hey 2, 100, DB1
Ive, "H... | You can use `CASE` for each column after you have made a join:
```
SELECT
COALESCE(t1.MyName COLLATE DATABASE_DEFAULT, t2.MyName ) AS MyName
,CASE WHEN t2.MyLevel > t1.MyLevel THEN t2.MyDescr COLLATE DATABASE_DEFAULT ELSE t1.MyDescr END AS MyDescr
,CASE WHEN t2.MyLevel > t1.MyLevel THEN t2.MyLevel ELSE... | The problem is that you're trying to say that one string is more than the other.
To compare the numeric value, you'll have to convert these to numbers somehow. A good start would be to use `substr(yourfieldname, n)` to cut of the text. Then you can use convert to typecast it to int; `convert(int, substr(nbr, 3)) <= 10... | Merge two tables in SQL and only get row with highest number | [
"",
"sql",
"sql-server-2008-r2",
"sql-view",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.